पाठ 2 / 25

Shebang, Permissions, PATH and Exit Codes

Create, run and exit a script correctly.

Anatomy of a script

A Bash script is a text file of commands. Its first line, the shebang, tells the kernel which interpreter to use: #!/usr/bin/env bash finds bash on the PATH (portable across systems where Bash lives in different places), while #!/bin/bash hard-codes the location. Make the file executable with chmod +x script.sh and run it as ./script.sh; the leading ./ is needed because the current directory is normally not on the PATH, the list of directories searched for commands. Every command returns an exit status: 0 means success, anything from 1 to 255 means failure (some values have conventions: 2 for misuse, 126 for not executable, 127 for command not found, 128 + N for death by signal N). $? holds the last command's status; exit N ends the script with a status. Scripts that report failures through exit codes compose well with other tools, CI pipelines and &&/|| chains.

A first script

Arguments, an exit code and a check of the previous command's status.

#!/usr/bin/env bash
# greet.sh - say hello and check that a directory exists

name="${1:-world}"            # first argument, default "world"
echo "Hello, $name!"

if ! ls /var/log > /dev/null 2>&1; then
    echo "cannot read /var/log" >&2   # errors go to stderr
    exit 1
fi

echo "done"
exit 0

# chmod +x greet.sh
# ./greet.sh Asha ; echo "exit status: $?"

A recipe card with a chef's name on top

The shebang is the line at the top of a recipe saying which chef should cook it. Without it, whoever picks up the card cooks it their own way, and the result may be quite different.

त्वरित जाँच: What does an exit status of 0 mean?

  • The command failed
  • The command was killed by a signal
  • The command was not found
  • The command succeeded
Answer

The command succeeded — By convention, 0 means success and non-zero means some kind of failure.