Question

This is the script:

file=$1
while getopts ":ivr" opt; do
case $opt in
i) iopt=1;;
v) vopt=1;;
r) ropt=1;;
\?)echo "invalid option: -$OPTARG" >
esac
done
shift $(($OPTIND-1))

So the only part I really understand is the shift $(($OPTIND-1)). Can someone explain what the rest is actually doing? Whats the meaning file=$1 at the top? Does that mean that the word "file" is now assigned to the value of the $1 column?

By the "$1 column" I am referring to the fact that when a command is run, $0 is assigned to the actual name of the command, $1 is the second options/argument given, and $2 is the third option/argument given. For example if you type:

rm -r directory/randomfiles

then $0 would be rm. -r would be $1. and directory/randomfiles would be $2. Does that make sense?

To summarise:

  1. what does the file=$1 at the top mean, whats the point of it?
  2. what does the $opt stand for, and what does it mean?
  3. what does the iopt=1 mean, and whats the point of it?
  4. if I wanted to use my script like this: MyScriptName -r [InsertFilenameHere] How would I go about it?

I know I'm asking a tonne - if you could just answer some of my questions, or point me in the right direction, I would much appreciate it!

Thanks in advance.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top