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

Time:12-12

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 $#?

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

#!/bin/bash

echo $1
echo $#

Thanks in advance.

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related