Operating System - HP-UX
1822827 Members
4564 Online
109645 Solutions
New Discussion юеВ

Re: scrit xyz -a cat -b dog -c mouse, what is $1, $2, $3, and $#?

 
SOLVED
Go to solution
Hanry Zhou
Super Advisor

scrit xyz -a cat -b dog -c mouse, what is $1, $2, $3, and $#?

Thanks,
none
4 REPLIES 4
John Kittel
Trusted Contributor

Re: scrit xyz -a cat -b dog -c mouse, what is $1, $2, $3, and $#?

# cat xyz
#!/usr/bin/sh
echo $1 $2 $3 $#
# ./xyz -a cat -b dog -c mouse
-a cat -b 6
#
Shannon Petry
Honored Contributor
Solution

Re: scrit xyz -a cat -b dog -c mouse, what is $1, $2, $3, and $#?

In scripting, very similar to coding arguments have specific identifiers.

In ksh, sh, bash, bash2, pdksh, etc...

$? - Return code of previous program

?# - Number of arguments passed to the script

$0 - name of script executing

$1 - First argument passed to the program

$2 - Second argument passed to the program

$22 - Twenty second argument passed to the program


If you are writing a program, use perl, etc.. you may want to utilize getopt where it is available. Quite handy.

Regards,
Shannon
Microsoft. When do you want a virus today?
Fred Ruffet
Honored Contributor

Re: scrit xyz -a cat -b dog -c mouse, what is $1, $2, $3, and $#?

getopt is also available for shell. A bit more complex than $1 but it manages "-a", "-b", etc for you.

regards,

Fred
--

"Reality is just a point of view." (P. K. D.)
A. Clay Stephenson
Acclaimed Contributor

Re: scrit xyz -a cat -b dog -c mouse, what is $1, $2, $3, and $#?

To answer your specific quest:
${1} = xyz
${2} = -a
${3} = -b
${#} = 7

You seem to want to know how to parse this. Man getopts (and their is also a getopt commnd) for details. Typically, you use getopts to extract all the options and then
use do a shift $((${OPTIND} - 1)) so that any remaining command line arguments without -a, -b, ... are now $1, $2, $3 ...
The getopts command sets ${OPTIND} for you; getopts is a better and more powerful version of getopt.
If it ain't broke, I can fix that.