Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between <EOF and <'EOF' in shell heredocs?

Tags:

shell

sh

I'm writing a .spec file for a module for linux build system and came across a small issue and wanted to share it.

For writing a script file :

cat <<EOF > /path/to/somewhere/script
#blah blah
EOF
chmod +x script

When the script ran on the target there were errors pointing to the location of the script as it were in the host system.Basically $0 was wrong.

Fixed it by changing the first line like this after seeing some sample code online:

cat <<'EOF' > /path/to/somewhere/script
#blah blah
EOF
chmod +x script

Wondering what's the difference and what made it work the second time.

like image 674
rroh Avatar asked Mar 15 '12 01:03

rroh


People also ask

What does << EOF mean in shell script?

This operator stands for the end of the file. This means that wherever a compiler or an interpreter encounters this operator, it will receive an indication that the file it was reading has ended.

What is EOT and EOF?

On a serial connection an EOT (End Of Transmission) character indicates a desire to end the transmission. Serial connections are usually accessed using a file driver. When the serial transmission ends, the file driver reports this as an EOF (End Of File) condition. EOF is not a character.

How do you use EOF and cat?

cat with <<EOF>> will create or append the content to the existing file, won't overwrite. whereas cat with <<EOF> will create or overwrite the content.

How do you use EOF in a for loop?

Rules for using end-of-file (eof( )):Always test for the end-of-file condition before processing data read from an input file stream. 2. Use a while loop for getting data from an input file stream. A for loop is desirable only when you know the exact number of data items in the file, which we do not know.


2 Answers

The difference is that in this version:

<<EOF
...
EOF

the ... functions roughly as a double-quoted string, performing parameter-expansions and command-substitutions and so on (specifically, in your case, replacing $0 with the value of $0), whereas in this version:

<<'EOF'
...
EOF

the ... functions roughly as a single-quoted string, and no such expansions are performed.

(See §3.6.6 "Here Documents" in the Bash Reference Manual.)

like image 155
ruakh Avatar answered Sep 26 '22 03:09

ruakh


The difference is whether the dollars and back quotes in the body of the here document are interpreted as the here document is expanded.

$ XYZ=pqr
$ cat <<EOF
> echo $XYZ
> EOF
echo pqr
$ cat <<'EOF'
> echo $XYZ
> EOF
echo $XYZ
$

You can try similar tricks with $(...).

like image 21
Jonathan Leffler Avatar answered Sep 22 '22 03:09

Jonathan Leffler