Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a bash script inside a bash script that uses special variables $1, $#

I’m trying to create a script that creates an other script that uses $1 and $#, the problem is that those variables are being interpreted by the first script, so they are empty. Here’s my problem, the first script creates the script /tmp/test.sh

#!/bin/bash

cat << EOF > /tmp/test.sh 
#!/bin/bash

echo $1
echo $#
EOF

The result in /tmp/test.sh:

#!/bin/bash

echo 
echo 0

Does anyone know how to avoid this and get in /tmp/test.sh $1 and $#?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like to have in /tmp/test.sh:

#!/bin/bash

echo $1
echo $#

Thanks in advance.

>Solution :

Quote the here-document delimiter so that the contents of the here document are treated as literal text (i.e., as if occurring in a single-quoted string).

cat << 'EOF' > /tmp/test.sh 
#!/bin/bash

echo $1
echo $#
EOF

Any quoting will work, not just single quotes. The only important thing is that at least one character be escaped.

  • cat << \EOF
  • cat << "EOF"
  • cat << E"O"F
  • etc
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading