You can use echo
to show lots of lines in bash. But cat
is simpler and easier to read.
How to do it
When we want to show multiple lines, we can use cat
to read the lines into the script and display them.
We start with a starter cat<<end_word
and we can put lines in until we begin a line with the end_word
. Usually the end_word
is EOF
, but it can be any word, Thatisit
or HELLO
. Just make sure that your end_word
is the same in both places.
cat<<end_word
We can put whatever we want
here
and
bash
will
show
it
exactly
end_word
The above means “read the input until the end_word
is reached.”
Thus if we cant to show a lot of lines in a shell script we can use cat
and then read them in:
cat<<EOF
Just some things to say
on a few lines
without lots of echos
EOF
And that will show:
Just some things to say
on a few lines
without lots of echos
Escaping Variables
If we put $
in the input, it will be treated as a variable. So we just have to comment it out:
x=3
cat<<EOF
We want to know what x is:
\$x = $x
EOF
This outputs:
We want to know what x is:
$x = 3
This can be really nice if we need to output a lot of variables:
x=1
cat << EOF
Show $x
Then 2
Then $(($x + 2)
EOF
Will print:
Show 1
Then 2
Then 3
And if you don’t want cat<<
to do variable substitution, then put ''
around EOF
:
cat << 'EOF'
Print $this as is
EOF
Output to a file
To output to a file (note that a single >
overwrites the file):
total=12
cat << EOF > /path/to/file
The total is $total
EOF
The file will contain:
The total is 12
And to just add to the file use >>
total=24
cat << EOF >> /path/to/file
The total is $total
EOF
The file will now contain:
The total is 12
The total is 24