Hello
I want to use options in my script and want to execute like this.
Code:
myscript -o a input.file output.file
Where -o is some mandatory option.
Following is my script:
Code:
#!/bin/bash
ShowHelp() {
echo "Some help"
}
MyFunction() {
echo "\$1 = $1"
echo "\$2 = $2"
echo "\$3 = $3"
}
while getopts ":ho:" opt ; do
case $opt in
h)
ShowHelp
;;
o)
MyFunction "$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG"
;;
:)
echo "Option -$OPTARG requires an argument."
exit 1
;;
esac
done
These are the results:
Code:
$ test.sh -a
Invalid option: -a
$ test.sh -o
Option -o requires an argument.
$ test.sh -o a
$1 = a
$2 =
$3 =
$ test.sh -oa
$1 = a
$2 =
$3 =
So far so good. But if I add $2 (input.file) and $3 (output.file) , then results will be strange.
Changes in my script:
Code:
.
.
o)
MyFunction "$OPTARG" "$2" "$3"
.
.
Result:
Code:
$ test.sh -oa input.file output.file
$1 = a
$2 = input.file
$3 = output.file
$ test.sh -o a input.file output.file
$1 = a
$2 = a
$3 = input.file
As you can see from the results, $1 will always be
a, doesn't matter there is a space in between option or not. But $2 and $3 will have different values based on that space between the option and its argument. I don't want this to happen.
I want $1 $2 and $3 to hold same values irrespective of there is space or not in between them.
Code:
$ test.sh -oa input.file output.file
$ test.sh -o a input.file output.file
..be same.
How to do it?
Any help really appreciated.
Thanks