Ad space (banner)
Lesson 18 / 20

Argument checks and error handling

This lesson covers the basics of argument checking and error handling — what makes a script safe to run.

The foundation of a safe script is to check the argument count and, if it is not what you expected, print a message and stop: if [ $# -eq 0 ]; then ... exit 1; fi. The number given to exit reaches the caller as the exit status.

The sample code shows the classic shape for the case where a required argument was not supplied: print an error message and stop abnormally with exit 1.

A common early stumble is writing no error checking at all and diving straight into the real work. A script that behaves mysteriously, with no error message, when given unexpected input is a reliable source of trouble in production.

In professional work, making sure a failure is noticed immediately is treated as central to running automation scripts safely.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Shell Script directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)