I am writing a shell script which accepts at most 2 options. However, I have a problem. Could you help me with it? (Let's say the name of this script is command
.)
#!/bin/bash
PROGNAME=$(basename $0)
for OPT in "$@"
do
echo "OPT: $OPT"
case "$OPT" in
'-p' | '--password' )
if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]]
then
echo "$PROGNAME: option requires an argument -- '$(echo $1 | sed 's/^-*//')'"
exit 2
fi
PASSWORD="$2"
shift 2
;;
'-u' | '--user' )
if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]]
then
echo "$PROGNAME: option requires an argument -- '$(echo $1 | sed 's/^-*//')'"
exit 2
fi
USER="$2"
shift 2
;;
* )
echo "$1"
echo "$PROGNAME: illigal option or argument -- '$(echo $1 | sed 's/^-*//')'"
exit 1
;;
esac
done
echo "GOOD"
Test1
$./command
GOOD
Test2
$./command -u user
OPT: -u
OPT: user
command: illigal option or argument -- ''
(The fourth line is empty.)
Test3
$./command -u user -p passwd
OPT: -u
OPT: user
-p
command: illigal option or argument -- 'p'
Same things happens to all -u, --user, -p and --password. I have 3 questions.
1) Why does "OPT: user" show up in test2 and test3?
2) Why does this code cause errors if I give one option to it?
3) How can I fix this code? I really appreciate your help!
getopts
– steeldriver Aug 27 '16 at 13:46