My script has an option o
, which should accept argument as value, as below
./script -o '-p 2' ls
but getopt is not allowing, giving an error
Unrecognized option '-p 2'
code snippet:
ARGS=$(getopt -a -n $0 -o o::h -- "$@")
eval set -- "$ARGS"
while true
do
case "$1" in
-o) opt="$2"; echo "options: $2"; shift; shift;;
-h) echo "$usage"; exit 0;;
--) cmd="$2"; shift; break;;
esac
done
How can I pass arguments as value to script?
Flows
You should use getopts
following a tutorial
#!/bin/bash
while getopts "o:h" opt; do
case $opt in
o) option="$OPTARG"; echo "options: $option";;
h) echo "$usage"; exit 0;;
esac
done
cmd="${@: -1}" # Warning: Get the last argument, even if it doesn't exist !
getopt is buggy and obsolete, please try getopts
.
来源:https://stackoverflow.com/questions/37784147/getopt-not-accepting-argument-value-starting-with-hyphen