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.
#!/bin/bash

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 ]
then
	show_usage
	exit 1
fi

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

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

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 *