KSH script arguments
BURNS,JIM
gt0178a at prism.gatech.EDU
Thu Aug 30 12:33:49 AEST 1990
in article <b4CC02oVc3Jx01 at amdahl.uts.amdahl.com>, jonc at uts.amdahl.com (Jonathan Chang) says:
> How can I extract the last argument to a ksh script?
I'll answer your question 2 different ways. The more generic approach
would be to set each element of $* to a ksh array variable:
set a b c #set "command line parameters"
j=0 #index variable
for i #no parameters means use $*
do
arr[$j]=$i #set each array element
j=`expr $j + 1` #incr. index - spaces ARE significant
done
j=0
for i #echo values in a diff. loop
do
echo 'arg #'$j' is '${arr[$j]}
j=`expr $j + 1`
done
echo ${arr[`expr $# - 1`]} #last 2 stmts are equiv. for pos. parms.
j=`expr ${#arr[*]} - 1`;echo ${arr[$j]}# but this one is more array generic
its output is:
arg #0 is a
arg #1 is b
arg #2 is c
c
c
The second sol'n is a function I use to replace 'cp' to check that the
last argument to 'cp' resulting from a wildcard expansion is a directory
if the # of parms > 2. Old habits from MSDOS die hard, and I'm always
doing 'cp *pat' thinking that the 'destination' will default to my current
directory. It offers no protection from overwriting the last file on the
expanded command tail if the # of parms = 2. I just loop to find the last
parm.
cp () {
if [ $# -eq 0 ]
then /bin/cp #let /bin/cp print error msg
else
for i in $@ #find last parm
do
continue
done
if [ $# -le 2 -o -d $i ] #ok if # parms = 2, or last parm is
then /bin/cp $@ #directory. /bin/cp prints error msg
else #if # parms = 1
echo $i: not a directory
fi
unset i
fi
}
Note that ksh will complain about $* not being set if you provide no parms
and the ksh flag 'nounset' is on. Use 'set -o' to check your flags, and
'set +o nounset' to turn it off.
Just for fun, here's the same function in csh. It's a little less clean
since I can't get 'if..then..else' to work inside a alias. The 'set j=
garbage string' if the # of parms = 0 just sets a bogus directory name so
that the remaining if's don't croak on an unset $j. Note the body of the
alias is one line.
alias cp \
'set i=(\!*);set j=$i[$#i];if ( $#i == 0 ) /bin/cp;if ( $#i == 0 ) set j=CB6EHVC;if ( $#i == 1 || $#i == 2 || -d $j ) /bin/cp \!*;if ( $#i >= 3 && \! -d $j && $j \!= CB6EHVC ) echo ${j}: not a directory;unset i;unset j'
--
BURNS,JIM
Georgia Institute of Technology, Box 30178, Atlanta Georgia, 30332
uucp: ...!{decvax,hplabs,ncar,purdue,rutgers}!gatech!prism!gt0178a
Internet: gt0178a at prism.gatech.edu
More information about the Comp.unix.questions
mailing list