1

From inside a bash script, I would like to create a file with a given content.
The content should contain variables expressions "$1", "$2"...

#!/bin/sh
cat < myfile
#!/bin/sh
command1 $1
command2 $2
command3 $3
EOF

The created file is meant to be used with variables:
./myfile param1 param2 param3

But myfile appears without the variables

$ cat myfile  

#!/bin/sh
command1
command2
command3

  • 1
    How are you creating the new script? If you are using echo commands, eg echo 'command1 $1', you must stop the expansion of the parameters in the calling script, so you must quote or escape them (as in echo command1 \$1), so that the $ is written literally. – AFH Mar 28 '17 at 11:10
1

The correct format should be:

#!/bin/sh
cat <<EOF > myfile
#!/bin/sh
command1 \$1
command2 \$2
command3 \$3
EOF

Two changes were made:

  • escape the $ using \
  • mark <<EOF at the beginning of the section which should be written to myfile (see here for more info)

After running this script, the result of

cat myfile 
#!/bin/sh
command1 $1
command2 $2
command3 $3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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