How can I say one of the options is required? can I use an if statement?
let say:
while getopts ":c:u:fp" opt; do
case $opt in
c) echo "-c was triggered, Parameter: $OPTARG" >&2;;
u) echo "-u was triggered, Parameter: $OPTARG" >&2;;
f) echo "-u was triggered, Parameter: $OPTARG" >&2;;
p) echo "-u was triggered, Parameter: $OPTARG" >&2;;
\?) echo "Invalid option: -$OPTARG" >&2;exit 1;;
*) echo "Option -$OPTARG requires an argument." >&2;exit 1;;
esac
done
Now I need to see if user requested one of the options -c or -u. it is necessary for the code.
if statement like the following wouldn't work:
if [ $opt != "c" ] then
echo "./script: Must select : -u or -c"
exit 1
fi
ctrue=N
utrue=N
while getopts ":c:u:fp" opt; do
case $opt in
c) ctrue=Y && echo "-c was triggered, Parameter: $OPTARG" >&2;;
u) utrue=Y && echo "-u was triggered, Parameter: $OPTARG" >&2;;
f) echo "-f was triggered, Parameter: $OPTARG" >&2;;
p) echo "-p was triggered, Parameter: $OPTARG" >&2;;
\?) echo "Invalid option: -$OPTARG" >&2;exit 1;;
*) echo "Option -$OPTARG requires an argument." >&2;exit 1;;
esac
done
# if C was entered or U was entered (and both cannot be Y or N ) this cannot be true
if [ "$utrue" = "$ctrue" ]; then
echo 'bad parameters'
else
echo 'required parameter entered'
fi
Made one or two other minor changes in the echo statements.
1 Like
I have this:
#!/bin/bash
# Argument = -t test -r server -p password -v usage()
{
cat << EOF
usage: $0 options
This script run the test1 or test2 over a machine.
OPTIONS:
-h Show this message
-t Test type, can be �test1 or �test2
-r Server address
-p Server root password
-v Verbose
EOF
}
TEST=
SERVER=
PASSWD=
VERBOSE=
while getopts �ht:r:p:v� OPTION
do
case $OPTION in
h)
usage
exit 1
;;
t)
TEST=$OPTARG
;;
r)
SERVER=$OPTARG
;;
p)
PASSWD=$OPTARG
;;
v)
VERBOSE=1
;;
?)
usage
exit
;;
esac
done
if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
usage
exit 1
fi
when I run any other options it gives me the message:
This is controlled by the command not my script and I don't have such a message. How can I get rid of that error?
---------- Post updated 03-31-12 at 11:43 AM ---------- Previous update was 03-30-12 at 08:56 PM ----------
haha! I found the problem. it was wrong quotation!