0

There may be a question out there for this somewhere. But I wasn't able to find it easily.

Basically I want to write a bash script on a new box. A script that I've previously used.

Example:

#!/bin/bash -ex
hi='hello world!'
echo $hi

I've always used (for multiline output)

cat > script.sh <<EOF
#!/bin/bash -ex
hi='hello world!'
echo $hi
EOF

But as you may have noticed this has issues with $hi, and other symbols. Is there a good way to do this? Tips Tricks?

2 Answers2

1

I think I may have figured it out. Still interested in how others solve this problem:

cat > script.sh <<'EOF'
#!/bin/bash -ex
hi='hello world!'
echo $hi
EOF

As a note, it seems like freebsd requires:

cat > script.sh <<'EOF'
#!/bin/bash -ex
hi='hello world!'
echo $hi
'EOF'
1

You should quote the End-Of-File marker, otrherwise the variable expansion (or rather, everything starting with a $, will get the current context.

Compare:

hi=here
cat >file.sh <<EOF
#!/bin/sh
hi=there
echo $hi
EOF
sh file.sh

(outputs here)

hi=here
cat >file.sh <<\EOF
#!/bin/sh
hi=there
echo $hi
EOF
sh file.sh

outputs there

hi=here
cat >file.sh <<'EOF'
#!/bin/sh
hi=there
echo $hi
EOF
sh file.sh

outputs there.

Alternatively, you can quote the $:

hi=here
cat >file.sh <<EOF
#!/bin/sh
hi=there
echo \$hi
EOF
sh file.sh

(outputs there)

This initially surprising behavior comes in very handy when there is a need to generate slightly different scripts for various purposes.

joepd
  • 2,397