Linux: check argument count, display usage, check user

Here is the code skeleton I use for my shell scripts.

It does the following:

  • Check the number of arguments. In this case, it it’s less than 1, it will display the usage.
  • Display the usage if -h or the –help is given as first argument.
  • Checks whether the right user runs the script. In the example, I check whether it’s root.

show_usage() {
	echo -e "Usage: $0 [OPTIONS...] [OTHER ARGUMENTS]"
	echo ""
	echo "options:"
	echo -e "\t-option1 meaning"

show_wrong_user() {
	echo "This script must be run by root. Current user: $USER"

if [ $# -lt 1 ]
	exit 1

if [[ $1 == "-h" ||$1 == "--help" ]]
	exit 0

if [[ $USER != "root" ]]; then
	exit 1

echo "Doing something with arguments $*"

$# returns the number of arguments provided to the script.
$0 returns the path to the script as used to start it (so could be a relative or absolute path).
$1 returns the first argument.
$* returns a string with all arguments.
$USER returns the login name of the current user.

echo displays the specified string. If the -e argument is provided, it will interpret backslash escape characters (e.g. \t, \n…).
the exit code 0 means that no error occurred. exit 1 returns the error return code 1 to the calling script.

Leave a Reply

Your email address will not be published. Required fields are marked *