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?

marked as duplicate by muru, John, Jeff Schaller, dhag, jimmij Dec 23 '15 at 21:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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.

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'
  • What shell are you using on FreeBSD? – muru Dec 23 '15 at 19:50
  • markdown isn't being my friend. But -bash, through sudo su – Dishcandanty Dec 23 '15 at 19:53
  • Check with bash --version. – muru Dec 23 '15 at 19:57
  • GNU bash, version 4.3.42(1)-release (amd64-portbld-freebsd10.1) – Dishcandanty Dec 23 '15 at 20:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.