lundi 2 mars 2015

How do I use inserted values using getopts


I have this bash code combined with getopts and if I understood getopts correctly OPTIND contains the index of the next command line option and all the command line options provided to shell script are presented in the variables $1, $2, $3 etc.. Correct me if I am wrong but basically the same concept as local variables in the functions.


So according to this why options [-a somevalue ] or [-b somevalue ] won't give me any results. What am I doing wrong?



OPT_A=A
OPT_B=B

while getopts :a:b FLAG; do
case $FLAG in
a)
OPT_A=$OPTARG
;;
b)
OPT_B=$OPTARG
;;
esac
done

shift $((OPTIND-1))

while [ $# -ne 0 ]; do

if [[ -z $OPT_A ]]; then
if [ `echo $1 | grep -o '\.' | wc -l` -ne 3 ]; then
echo "Parameter '$1' does not look like an IP Address (does not contain 3 dots).";
exit 1;
elif [ `echo $1 | tr '.' ' ' | wc -w` -ne 4 ]; then
echo "Parameter '$1' does not look like an IP Address (does not contain 4 octets).";
exit 1;
else
for OCTET in `echo $1 | tr '.' ' '`; do
if ! [[ $OCTET =~ ^[0-9]+$ ]]; then
echo "Parameter '$1' does not look like in IP Address (octet '$OCTET' is not numeric).";
exit 1;
elif [[ $OCTET -lt 0 || $OCTET -gt 255 ]]; then
echo "Parameter '$1' does not look like in IP Address (octet '$OCTET' in not in range 0-255).";
exit 1;
fi
done
fi
fi


if [[ -z $OPT_B ]]; then
if [[ "$2" =~ ^[0-9]+$ ]] && [ "$2" -ge 1 -a "$2" -le 10000 ]; then
echo "chosen variable: $2";
exit 1;
else echo "variable $2 is not in range '1 - 10000'";
exit 1;
fi
fi

done
exit 0


Aucun commentaire:

Enregistrer un commentaire