Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!zaphod.mps.ohio-state.edu!wuarchive!ukma!uflorida!stat!sun13!prism!gt0178a From: gt0178a@prism.gatech.EDU (BURNS,JIM) Newsgroups: comp.unix.questions Subject: Re: KSH script arguments Message-ID: <13160@hydra.gatech.EDU> Date: 30 Aug 90 02:33:49 GMT References: Distribution: comp.unix.questions Organization: Georgia Institute of Technology Lines: 72 in article , jonc@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@prism.gatech.edu