Reading Input and Handling Script Arguments

Ask users for input with read, accept arguments and flags when a script is launched, and exit with meaningful status codes.

~6 min Beginner

Two ways to give a script information

  1. Ask while it runs. The script pauses and asks a question. This uses the read command.
  2. Pass it at launch. You type extra words after the script name. These are called arguments.

Asking with read

#!/bin/bash
read -p "What is your name? " name
echo "Nice to meet you, $name"

read waits for the user to type a line and stores it in the variable. -p shows a prompt first. More options:

read -s -p "Password: " pass
read -t 5 -p "Quick, answer: " answer
read -n 1 -p "Continue? (y/n) " key
  • -s hides what is typed, which is good for passwords.
  • -t 5 gives up after 5 seconds.
  • -n 1 reads a single key without waiting for Enter.

Arguments at launch

Anything typed after the script name is available inside the script as numbered variables.

./greet.sh Alex London
  • $0 is the script name (./greet.sh)
  • $1 is the first argument (Alex)
  • $2 is the second argument (London)
#!/bin/bash
echo "Hello $1 from $2"

Counting and listing arguments

  • $# is the number of arguments.
  • $@ is all the arguments, with each one kept as a separate word when quoted as "$@".
#!/bin/bash
echo "You passed $# arguments"
for arg in "$@"; do
    echo "Argument: $arg"
done

Validating arguments

A good script checks its input and explains how to use it when something is missing.

if [ $# -ne 1 ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

-ne means "not equal", so this runs when the number of arguments is not exactly 1. The message shows the correct usage, and exit 1 stops the script with a failure code.

Default values

name="${1:-friend}"
echo "Hello, $name"

${var:-default} uses default when the variable is empty or not set. Here, running the script with no argument prints Hello, friend.

Flags with getopts

Many programs accept flags such as -v or -n 5. The built-in getopts reads them.

#!/bin/bash
verbose=0
count=1
while getopts "vn:" opt; do
    case "$opt" in
        v) verbose=1 ;;
        n) count="$OPTARG" ;;
    esac
done

The string "vn:" lists the allowed flags. A letter followed by a colon, here n:, takes a value. That value is stored in $OPTARG. A flag without a colon, here v, is just on or off.

Exit codes

Every program ends with an exit code, a number that tells whether it worked.

exit 0
exit 1
  • 0 means success.
  • Any other number means a problem. Use different numbers for different problems, for example 1 for bad usage and 2 for a missing file.

The caller reads the code from $?. Tools such as if and && use it to decide what to do next.

Sign up to track your progress Mark lessons as read and pick up where you left off Sign up free to unlock this practice Your first practice lesson is free to try. Create an account to unlock the rest and save your progress