views:

47

answers:

4

I'm trying to tell unix to print out the command line arguments passed to a Bourne Shell script, but it's not working. I get the value of x at the echo statement, and not the command line argument at the desired location.

This is what I want:

./run a b c d

a b c d

this is what I get:

1 2 3 4

What's going on? I know that UNIX is confused as per what I'm referencing in the shell script (the variable x or the command line argument at the x'th position". How can I clarify what I mean?

#!/bin/sh
x=1
until [ $x -gt $# ]
do
echo $x
x=`expr $x + 1`
done

EDIT: Thank you all for the responses, but now I have another question; what if you wanted to start counting not at the first argument, but at the second, or third? So, what would I do to tell UNIX to process elements starting at the second position, and ignore the first?

+1  A: 
echo $*

$x is not the xth argument. It's the variable x, and expr $x+1 is like x++ in other languages.

Lou Franco
Hmm... okay. But what if I wanted to start printing out at the second argument? So instead of printing a b c d, it would just print out b c d?
Waffles
+1  A: 

The simplest change to your script to make it do what you asked is this:

#!/bin/sh
x=1
until [ $x -gt $# ]
do
    eval "echo \${$x}"
    x=`expr $x + 1`
done

HOWEVER (and this is a big however), using eval (especially on user input) is a huge security problem. A better way is to use shift and the first positional argument variable like this:

#!/bin/sh

while [ $# -gt 0 ]; do
    x=$1
    shift
    echo ${x}
done
kanaka
As an added note, if you are using functions, then the positional arguments are the function arguments and not the program arguments. Which is useful, but something to be aware of.
kanaka
A: 

A solution not using shift:

#!/bin/sh

for arg in "$@"; do
  printf "%s " "$arg"
done
echo
enzotib
+1  A: 

If you want to start counting a the 2nd argument

for i in ${@:2}
do
  echo $i
done
ghostdog74