ruebenramirez / blog

My blog
http://blog.ruebenramirez.com/
7 stars 0 forks source link

multi-line strings in bash #278

Open ruebenramirez opened 8 years ago

ruebenramirez commented 8 years ago

http://stackoverflow.com/a/21549836

Examples of Bash cat <<EOF syntax usage:

1. Passing multiline string to a variable:
$ sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)
The $sql variable now holds newlines as well, you can check it with echo -e "$sql" cmd.

2. Passing multiline string to a file:
$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF
The print.sh file now contains:

#!/bin/bash
echo $PWD
echo /home/user
3. Passing multiline string to a command/pipe:
$ cat <<EOF | grep 'b' | tee b.txt | grep 'r'
foo
bar
baz
EOF
This creates b.txt file with both bar and baz lines but prints only the bar.