Hone

Lessons · Terminal · a script with a shebang

A script: commands in a file, run as one

A script is a text file of commands with a first line naming its interpreter, #!/usr/bin/env bash. chmod +x it and ./name runs it; $1, $# and "$@" are its arguments.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Anything you type twice belongs in a script. Every deploy, backup and setup routine on every team is one.

How to think about it

Start with the shebang, then set -e so the script stops at the first failure, then the commands you already ran by hand.

Worked example

printf '#!/usr/bin/env bash\nset -e\necho "args: $#"\nfor a in "$@"; do echo "- $a"; done\n' > greet.sh
A script that lists its arguments.
chmod +x greet.sh
Make it runnable.
./greet.sh one "two words"
args: 2, then - one, then - two words: the quoted argument stayed whole.

Your turn

Name the interpreter on the first line.

#!/usr/bin/env 

The trap

A script without set -e keeps going after a failed step, so a backup that could not read its source still deletes the old backup.

Practise a script with a shebang on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.