I am pretty new to shell scripting and I have to add a flag (getopts
) to my script where I can overwrite download url command if the script can't reach the url for any reason. For instance, if I add my flag then it won't terminate my script, I can choose to continue if url can't be reached.
Currently, I have
if "$?" -ne "0" then
echo "can't reach the url, n\ aborting"
exit
Now I need to add a flag through getopts
where I can choose to ignore "$?' - ne "0"
command,
I don't know how getopts works, I am pretty new to it. Can someone please help me on how to go about it?
If you only have one option, sometimes it's simpler to just check $1
:
# put download command here
if (( $? != 0 )) && [[ $1 != -c ]]; then
echo -e "can't reach the url, \n aborting"
exit
fi
# put stuff to do if continuing here
If you're going to accept other options, some possibly with arguments, the getopts
should be used:
#!/bin/bash
usage () { echo "Here is how to use this program"; }
cont=false
# g and m require arguments, c and h do not, the initial colon is for silent error handling
options=':cg:hm:' # additional option characters go here
while getopts $options option
do
case $option in
c ) cont=true;;
g ) echo "The argument for -g is $OPTARG"; g_option=$OPTARG;; #placeholder example
h ) usage; exit;;
m ) echo "The argument for -m is $OPTARG"; m_option=$OPTARG;; #placeholder example
# more option processing can go here
\? ) echo "Unknown option: -$OPTARG"
: ) echo "Missing option argument for -$OPTARG";;
* ) echo "Unimplimented option: -$OPTARG";;
esac
done
shift $(($OPTIND - 1))
# put download command here
if (( $? != 0 )) && ! $cont; then
echo -e "can't reach the url, \n aborting"
exit
fi
# put stuff to do if continuing here