Your command can take up to 3 command line options, -i
, -r
, -v
. The getopts
command is executed in a loop to parse the options. The getopts command uses the opt
variable to hold the current option character. There are some variables set in the case command to remember which options were given to the script.
You're right about the use of $1
, but normally you would not extract positional parameters until the options have been shifted.
To do MyScriptName -r [InsertFilenameHere]
, you would do this:
#!/bin/bash
ropt=0
while getopts :r opt; do
case $opt in
r) ropt=1;;
?) echo "illegal option: -$OPTARG"; exit 1;;
esac
done
shift $((OPTIND-1))
file=$1
if [[ $ropt == 0 ]]; then
echo "error: you did not specify '-r'"
exit 1
fi
: do something with $file