How to create a file using shell script (heredoc)?

How to create a file using shell script (heredoc)?

The TLDR answer:

If you need to use a shell script which would create a file with the dynamic content using few variables then you can use the code below. The approach we shall take here will use heredoc / here document syntax.

cat << EOF > demo.txt
cd "$HOME"
echo "$PWD" # echo the current path
echo "this is plain text"
EOF
file-creation.sh

Would create a file which will create a new file named demo.txt

cd "/home/thetldr-tech"
echo "/home/thetldr-tech/demo"
echo "this is plain text"
demo.txt

Where can we use this?

  • Use it when you want to automate to create some file in the server.
  • Use it in CloudFormation to create new files using EC2 launch templates.
  • Use it to create files which can be used in AWS code deploy hooks.