🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Input Validation

Input validation is the check of script input before the script uses it. Bad input is caught early, so later commands never see it.

Wrong count prints usage and exits

The script needs two arguments and gets none. The usage line goes to stderr, and the exit status is 1.

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <first> <second>" >&2
  exit 1
fi
echo "two args given"

A missing tool is caught before use

command -v checks for grep without printing its path. The ready line prints only when the tool is found.

if ! command -v grep >/dev/null 2>&1; then
  echo "grep is missing"
  exit 1
fi
echo "grep is ready"

Digits pass, other text fails the check

The check function accepts a value made of digits only. The value 4x fails because it holds a letter.

check() {
  case "$1" in
    ''|*[!0-9]*) echo "$1 is not a number" ;;
    *) echo "$1 is valid" ;;
  esac
}
check 42
check 4x

Example

if [ "$#" -ne 1 ]; then
  echo "Usage: $0 <number>" >&2
  exit 1
fi
if ! command -v sort >/dev/null 2>&1; then
  echo "sort is missing" >&2
  exit 1
fi
case "$1" in
  ''|*[!0-9]*) echo "not a number: $1" >&2; exit 1 ;;
esac
echo "number is $1"
echo "double is $(( $1 * 2 ))"

Key points

  • Argument count: check $# first, before any argument is used.
  • Usage message: one line that shows the expected arguments.
  • Non-zero exit: a status that tells the caller the script failed.
  • command -v: a test that reports whether a tool is installed.
  • Number check: a case pattern that accepts digits and rejects the rest.
  • Fail early: stop at the first bad input, not halfway through the job.

In this example, the script first checks that it got exactly one argument. It then checks that sort is installed, using command -v. Next, a case pattern rejects any value that is not all digits. Only then does it print the number and its double.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A script needs exactly one number argument. It is run with no arguments. What should it do?