Cancel

Heredoc in Bash

You can run any program within a shell script without user action by supplying the required input for the interactive program.

EOF operator stands for the end of the file. This means that wherever a compiler or an interpreter encounters this operator, it will receive an indication that the file it was reading has ended.

Insert data into the file without using the echo command.

1
2
3
cat <<EOF > demo.txt
hello world
EOF

You can also use variables here, cat command will execute variables automatically. To avoid execution automatically, use a special character backslash.

1
2
3
4
cat <<EOF > demo.sh
Hello, world
whoami=\$HOME
EOF

You can use heredoc to create a template like this. Run the following command as an example.

1
2
3
4
5
6
7
8
9
cat <<EOF
Usage: <command_name> [option]
Description: Your description.
Options:
  -u  Update
  -h  Show the help
  -v  Get the tool version
  -d  Show detailed information
EOF