This post explores the cat <<EOF syntax in Bash, a powerful tool for handling multi-line text. It’s particularly useful when assigning a multi-line string to a shell variable, a file, or piping it into another command. The examples below are adapted from a detailed (Stack Overflow discussion)[https://stackoverflow.com/questions/2500436/how-does-cat-eof-work-in-bash]

Examples of “cat «EOF syntax usage in Bash”:

Assign multi-line string to a shell variable

Using cat <<EOF, you can easily assign a multi-line string to a shell variable. Here’s an example:

$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)

In this case, the variable $sql retains the new-line characters. You can confirm this by printing it with echo -e "$sql".

Passing a Multi-line String to a File in Bash

You can also direct a multi-line string into a file using this syntax:

$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF

The resulting print.sh file will contain the following lines:

#!/bin/bash
echo $PWD
echo /home/user

This script, when executed, will print the current working directory twice, illustrating how variables are expanded within the heredoc.

Passing a Multi-line String to a Pipe in Bash

The cat <<EOF syntax can be combined with pipes for efficient text processing. For instance:

$ cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF

This command will output lines containing ‘b’ to both the standard output (stdout) and a file named ‘b.txt’. In this example, b.txt will contain the lines ‘bar’ and ‘baz’.

Conclusion

The cat <<EOF syntax in Bash is an elegant solution for managing multi-line strings. Whether it’s assigning text to variables, redirecting output to files, or working with pipes, this syntax simplifies script writing and enhances readability. As demonstrated in these examples, it’s a versatile tool that can be adapted to various scripting needs.

Reference

Tags:

Updated: