Mainframe Path Start learning free
Beginner7 min readLesson 5 of 5

Your first shell script and exit codes

A shell script is a text file of commands that runs from top to bottom. It starts with a #! line saying which shell runs it, needs execute permission, and ends with an exit status: 0 means success and anything else means failure, the same idea as a mainframe return code.

A small, real script

backup.sh
#!/bin/bash
# Copy the application config to a dated backup and report the result.
set -euo pipefail

SRC="${1:-/etc/myapp/app.conf}"      # first argument, or a default
DEST="/var/backups/app.conf.$(date +%Y%m%d)"

if [ ! -f "$SRC" ]; then
  echo "No such file: $SRC" >&2
  exit 2
fi

cp "$SRC" "$DEST"
echo "Backed up $SRC to $DEST"

Running it

Make it executable, run it, check the result
$ chmod +x backup.sh
$ ./backup.sh /etc/myapp/app.conf
Backed up /etc/myapp/app.conf to /var/backups/app.conf.20261009
$ echo $?
0

The ./ matters. The shell only searches the folders listed in PATH for commands, and the current folder is normally not one of them, so you say explicitly 'the script here'.

Exit status: Linux's return code

Every command ends with an exit status from 0 to 255, and $? holds the last one. 0 means success, and any other value means failure. That is the same idea as a z/OS step's return code, except that Linux has no 'warning' convention like RC 4: anything other than 0 counts as failed. Pipelines rely on this. Jenkins marks a step as failed when its command exits with a non-zero status.

set -euo pipefail, the safety lineWhat it means
-e
Stop the script as soon as a command fails, instead of carrying on regardless.
-u
Treat an unset variable as an error, so a typo in a name cannot quietly become an empty value.
-o pipefail
A pipeline fails if any command in it fails, not only the last one.
TRY IT YOURSELF

Which special variable holds the exit status of the last command?

Show a hint

A dollar sign and a question mark.

Show the solution

$?. Run echo $? straight after the command to see it.

Examples are for learning. Run commands and jobs only on a system you are authorised to use, such as a training or test system, and never on production without approval.

Common mistakes

Forgetting the shebang or the execute bit

Without #!/bin/bash the wrong shell may run it, and without chmod +x you get 'Permission denied'.

Leaving variables unquoted

A file name with a space splits into two arguments. Write "$FILE", not $FILE.

Ignoring failures in the middle of a script

Without set -e the script carries on after an error and reports success at the end. Pipelines then go green when they should be red.

What you will see at work

Key terms

Check your understanding.
Take this lesson's quiz and save your progress. Free.

Take the lesson quiz
← Processes, services and remote accessBack to Linux command line basics