
When working with shell scripts, handling command-line arguments efficiently is crucial for making scripts flexible and reusable. The
function explained in this article will give you a great example of how to handle command line args.
High level flow
In principle what we need is a function capable of ensuring that all the command-line arguments are correctly processed and assigned to the relevant variables. Starting from this we will need also a method that will print the script usage, as help menu in case some parameters are missing. If we put these thing together we will have this high level flow:
- Check that the number is greater than 0
- if this condition is not met, print the helper and exit
- else start to parse all the arguments and assign to the proper variables
The helper function
The helper/print help menu function is nothing more than a bunch of echo, so assuming that our script accepts 3 parameters and must be invoked as my-script.sh or ./my-script -p my-param1 -d my-param2 -f my-param3
This function will look like
usage() {
echo "Usage: $0 -p <parameter> -d <directory> -f <file>"
echo " -p,--param: Parameter we want to store"
echo " -d,--directory: Directory to search"
echo " -f,--file: File to write"
exit 1
}
Iterating over arguments
The function then enters a loop to process each argument:
while [ $# -gt 0 ]; do
.... do something
done
The above code will ensure that all the arguments are processed one by one, now we need to identify the flags used and assign to the proper variable, for doing this we will need a case switch within the loop that will go through one by one, identify and assign
case "$1" in
-p|--param) shift; PARAM=$1; shift;;
-d|--directory) shift; DIRECTORY=$1; shift;;
-f|--file) shift; FILENAME=$1;shift;;
-\?|-h|--help) shift; usage;;
*) shift;;
esac
Final Function
If we put all the above together we will have this function
handle_args() {
[ $# -gt 0 ] || usage
while [ $# -gt 0 ]; do
case "$1" in
-p|--param) shift; PARAM=$1; shift;;
-d|--directory) shift; DIRECTORY=$1; shift;;
-f|--file) shift; FILENAME=$1;shift;;
-\?|-h|--help) shift; usage;;
*) shift;;
esac
done
}
Job done!
The final script
The final script will put everything together and call the function for handling the args
PARAM=
DIRECTORY=
FILENAME=
usage() {
echo "Usage: $0 -p <parameter> -d <directory> -f <file>"
echo " -p,--param: Parameter we want to store"
echo " -d,--directory: Directory to search"
echo " -f,--file: File to write"
exit 1
}
handle_args() {
[ $# -gt 0 ] || usage
while [ $# -gt 0 ]; do
case "$1" in
-p|--param) shift; PARAM=$1; shift;;
-d|--directory) shift; DIRECTORY=$1; shift;;
-f|--file) shift; FILENAME=$1;shift;;
-\?|-h|--help) shift; usage;;
*) shift;;
esac
done
}
# call the function
handle_args "$@"
echo "Program will be executed with these values:"
echo "- param = $PARAM"
echo "- directory = $DIRECTORY"
echo "- file = $FILENAME"
Job Done! Hope you will find this useful, please share and help us grow.

Share this content: