Operating System - HP-UX
1827870 Members
1292 Online
109969 Solutions
New Discussion

Passing parameters to script

 
SOLVED
Go to solution
Pat Peter
Occasional Advisor

Passing parameters to script

Hi,

I am writing a script in which I have to pass some command line arguments to the script.

For instance, my script's name is script.sh and it should have the following usage

script.sh -h -d date -v version.

ALso I should probably give a usage for the script where

script.sh -u

will give me the usage of all the parameters.

I have not done this before.

Can anyone please send me a sample code which has this kind of functionality.

Please help.

Thanks,
Pat
4 REPLIES 4
Bharat Katkar
Honored Contributor

Re: Passing parameters to script

Hi Pat,
I don't know what exactly you are looking for but with the given info i would do it this way using korne shell:

script.sh
---------

#!/usr/bin/ksh
list=$*
for i in $list
do
if [ "$1" -eq "-u" ]
then
echo $2 $3 ...
elif [ "$1" -eq "-h" ]
then
echo $2 $3 ...
fi
fi
done

This you can keep on putting if-then-fi as reuired or you can even use CASE statements.

See man sh for more information.

Hope that helps.
Regards,
You need to know a lot to actually know how little you know
Peter Godron
Honored Contributor

Re: Passing parameters to script

Pat,
if you have perl:

cat a.pl
#!/usr/contrib/bin/perl -s
print "value of -h: $h\n";
print "value of -d: $d\n";
print "value of -v: $v\n";

./a.pl -h=peter -d=20050224 -v=1.0
value of -h: peter
value of -d: 20050224
value of -v: 1.0

Regards
Jdamian
Respected Contributor

Re: Passing parameters to script

Read getopt(1) and getopts(1) manual pages for details of parsing command line.

Here there is an example:

FILENAME=""
VERBOSE=0
OPTIONS=ahF:V

while getopts "${OPTIONS}" OPTION 2> /dev/null
do
case ${OPTION} in
(a) echo "option 'a' selected"
;;
(F) FILENAME="${OPTARG}"
;;
(v) VERBOSE=1
;;
(h) print "usage: $(basename $0) [-a] [-v] [-F type]"
print "usage: $(basename $0) -h"
exit
;;
(\?) print -u2 "usage: $(basename $0) [-a] [-v] [-F type]"
print -u2 "usage: $(basename $0) -h"
exit 1
;;
esac
done
shift $(( ${OPTIND} - 1 ))

c_51
Trusted Contributor
Solution

Re: Passing parameters to script

you would do something like this:

program="${0:##*/}"

function usage {
print -u2 "$program [-d date -h name -v version | -u]"
}


while getopts :d:h:v:u OPTION
do
case "$OPTION" in
d) Date="$OPTARG";;
h) Name="$OPTARG";;
v) Version="$OPTARG";;;;
u) usage;exit;;
:) print -u2 "$program: $OPTARG is missing argument!"
usage
exit 1;;
\?) print -u2 "$program: $OPTARG is an invalid option!"
usage
exit 1;;
esac
done
shift $(( $OPTIND - 1 ))