Reputation: 6350
I am creating a bash script that will two argument from the user from command line . But i am not sure how I can take 2 argument from the user and both arguments are required if not passed will show error and return from the script . Below is the code i am using to take argument from the user , but currently my getopts is taking only one argument.
optspec="h-:"
while getopts "$optspec" optchar; do
case "${optchar}" in
-)
case "$OPTARG" in
file)
display_usage ;;
file=*)
INPUTFILE=${OPTARG#*=};;
esac;;
h|*) display_usage;;
esac
done
How could i add an an option to take one more args from command line. Like below
script.sh --file="abc" --date="dd/mm/yyyy"
Upvotes: 1
Views: 774
Reputation: 141020
getopts
does not support long arguments. It only supports single letter arguments.
You can use getopt
. It is not as widely available as getopts
, which is from posix and available everywhere. getopt
will be for sure available on any linux and not only. On linux it's part of linux-utils
, a group of most basic utilities like mount
or swapon
.
Typical getopt
usage looks like:
if ! args=$(getopt -n "your_script_name" -oh -l file:,date: -- "$@"); then
echo "Error parsing arguments" >&2
exit 1
fi
# getopt parses `"$@"` arguments and generates a nice looking string
# getopt .... -- arg1 --file=file arg2 --date=date arg3
# would output:
# --file file --date date -- arg1 arg2 arg3
# the idea is to re-read bash arguments using `eval set`
eval set -- "$args"
while (($#)); do
case "$1" in
-h) echo "help"; exit; ;;
--file) file="$2"; shift; ;;
--date) date="$2"; shift; ;;
--) shift; break; ;;
*) echo "Internal error - programmer made an error with this while or case" >&2; exit 1; ;;
esac
shift
done
echo file="$file" date="$date"
echo Rest of arguments: "$@"
Upvotes: 3