Hello,
I've got next problem:
I want to examine at the beginning of a script in an if loop that:
- Is there 4 parameters given
- If first state is true then: is there switches -e and -d?
- At the end, how can i indentify them as variebles regardlees to its order.
I was thinking like this if [ "$#" == 4 && "$1" == -e && "$3" == -d ] ; then ...
Can anyone help me?
If loop could be here the right choice, at all?
Regards
jaduks
2
You can use getopts here.
e.g.
[ $# -ne 4 ] && <some usage function> && exit
while getopts e:d: OPTION
do
case $OPTION in
e) somevar=$OPTARG ;;
d) somevar1=$OPTARG ;;
esac
done
There is no such thing as an if loop; if chooses between one or more sets of commands to execute depening on one or more conditions.
if [ $# -eq 4 ]
then
: do whatever
else
printf "4 parameters required\n" >&2
exit 1 ## or whatever
fi
They are called options, not switches.
Regard what as variables?
As jaduks pointed out, the usual method is to use getopts in a while loop.
However, it is easy enough to roll your own:
while [ $# -gt 0 ]
do
case $1 in
-e) var_e=$2
shift 2
;;
-d) var_d=$2
shift 2
;;
*) shift ;; ## ignore other arguments
esac
done