← All lessons
Processes and scripts · Lesson 4 of 7

Your first script

A shell script is a text file of commands, run top to bottom as if you'd typed them. The first line, the shebang, says which program runs the file. For Bash it's #!/bin/bash. Lines starting with # after that are comments.

#!/bin/bash
# hello.sh: greet someone
echo "Hello, $1!"
echo "You gave me $# arguments."

Save it, give it execute permission once with chmod +x hello.sh, and run it with its path:

$ chmod +x hello.sh
$ ./hello.sh Dana
Hello, Dana!
You gave me 1 arguments.

Inside a script, $1, $2 and so on are the arguments, $# is how many there are, $0 is the script's own name and "$@" is all of them, each kept whole.

Every command ends with an exit status: 0 means success and anything else means some kind of failure. $? holds the last one. Scripts end with exit 0 (fine) or exit 1 (something went wrong) so whatever ran them can tell.

Two lines that make scripts safer: set -e stops the script at the first command that fails, instead of carrying on and making things worse, and set -u treats a misspelled variable as an error instead of quietly using an empty value.

Practice

What is the first line of a Bash script?

More info

Quick reference

#!/bin/bashThe shebang: run this file with Bash.
chmod +x file; ./fileMake it runnable; run it.
$1 $2 … $# "$@" $0Arguments, how many, all of them, the script's name.
$?The last command's exit status (0 is success).
exit NEnd the script with status N.
set -e, set -uStop on failure; error on unset variables.

The other Linux courses