Reputation: 443
I am facing a problem while reading input from command prompt in shell script. My script's name is status.ksh, and I have to take parameter from command prompt. This script accepts 2 parameter. 1st is "-e" and second is "server_name".
When I am running the script like this,
status.ksh -e server_name
echo $@
is giving output "server_name" only, where as expected output should be "-e server_name"
and echo $1
is giving output as NULL, where as expected output should be "-e".
Please guide me, how to read get the 1st parameter, which is "-e" .
Thanks & Regards
Upvotes: 0
Views: 92
Reputation: 96266
The problem was caused by -e
. This is a flag for echo
.
-e enable interpretation of backslash escapes
Most of the unix commands allow --
to be used to separate flags and the rest of the arguments, but echo
doesn't support this, so you need another command:
printf "%s\n" "$1"
If you need complex command line argument parsing, definitely go with getopts
as Joe suggested.
Upvotes: 1
Reputation: 27247
Have you read this reference? http://www.lehman.cuny.edu/cgi-bin/man-cgi?getopts+1
You shouldn't use $1, $2, $@, etc to parse options. There are builtins that can handle this for you.
Example 2 Processing Arguments for a Command with Options
The following fragment of a shell program processes the
arguments for a command that can take the options -a or -b.
It also processes the option -o, which requires an option-
argument:
while getopts abo: c
do
case $c in
a | b) FLAG=$c;;
o) OARG=$OPTARG;;
\?) echo $USAGE
exit 2;;
esac
done
shift `expr $OPTIND - 1`
More examples:
http://linux-training.be/files/books/html/fun/ch21s05.html
http://www.livefirelabs.com/unix_tip_trick_shell_script/may_2003/05262003.htm
Upvotes: 0