Skip to content

Instantly share code, notes, and snippets.

@motey
Created August 25, 2023 10:17
Show Gist options
  • Save motey/5e57d84768a739c84826387af40ca008 to your computer and use it in GitHub Desktop.
Save motey/5e57d84768a739c84826387af40ca008 to your computer and use it in GitHub Desktop.
Bash script parse named arguments
#!/bin/bash
# My function header...
# Arguments:
# "--uid" or "-u" -> uid - int - default: 0 - user id for...
# "--gid" or "-g" -> gid - int - default: 0 - group id for...
# parse arguments
while [ $# -gt 0 ]; do
case "${1%%=*}" in
-u | --uid)
arg_uid="${1#*=}"
;;
-g | --gid)
arg_gid="${1#*=}"
;;
*)
printf "Error: Invalid argument: '${1%%=*}' \n"
exit 1
;;
esac
shift
done
# set argument defaults if necessary
if [ -z "$arg_uid" ]; then
arg_uid=0
fi
if [ -z "$arg_gid" ]; then
arg_gid=0
fi
echo "uid: $arg_uid"
echo "gid: $arg_gid"
@motey
Copy link
Author

motey commented Aug 25, 2023

Example Usage:

# ./parse.sh -u=23
uid: 23
gid: 0
# ./parse.sh -u=23 --gid=23
uid: 23
gid: 23
# ./parse.sh 12
Error: Invalid argument: '12'
# ./parse.sh -a=12
Error: Invalid argument: '-a'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment