Writing a shebang script

We can accomplish a self-executing script with a special syntax, #!, called a shebang, or sometimes hash-bang, as the first line of the script. This syntax is treated specially by the kernel, and specifies the program that should be used to run the rest of the script—the interpreter.

We edit hello.bash to put the shebang as the very first line of the script:

#!/bin/bash
printf 'Hello, %s!\n' "$USER"

The preceding syntax assumes that your Bash shell is in the common location of /bin/bash. You can find out where yours is by checking the value of the BASH variable:

bash$ declare -p BASH
declare -p BASH="/usr/local/bin/bash"

We also need to use the chmod system program to make the script executable:

bash$ chmod +x hello.bash ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.