Reputation: 1103
In my shell script, I am reading two optional parameters. The first parameter is not getting read. Given below is the code:
#! /bin/sh
while getopts "f:c:" opt;
do
case "${opt}" in
f) file=${OPTARG}
echo "" "File Name: ${file}"
;;
c) str=${OPTARG}
echo "" "String: ${str}"
;;
esac
done
When I am running my script:
$ sh myscript.sh -f filename.txt -c someString
Output:
$ File Name:
$ String: someString
Please let me know where am i going wrong. I have tried all options in getopts:
:f:c
f:c
f:c:
:f:c:
Upvotes: 0
Views: 138
Reputation: 785
You code is not working because of typo
c) str=${OPTAGR} echo "" "String: ${str}" ;;
here above you have typo in str=${OPTAGR}
it should be str=${OPTARG}
I have executed below piece of code and it worked fine
#! /bin/sh
while getopts "f:c:" opt;
do
case "${opt}" in
f) file=${OPTARG}
echo "" "File Name: ${file}"
;;
c) str=${OPTARG}
echo "" "String: ${str}"
;;
esac
done
Output
ajay@Ajay:~$ ./new.sh -f filename.txt -c sometext
File Name: filename.txt
String: sometext
Upvotes: 1