Script to iterate all command line arguments

Hi guys,

I am having trouble with this script. What i want it to do is to iterate all command line arguments in reverse order. The code below does this fine but i need the output to print the words on separate lines instead of one line:

#!/bin/bash
#Takes in the arguments and displays them in reverse order
if [ $# -eq 0 ]
then
       echo "No arguments entered in script $0, try again"
       exit 1
fi
arguments=""
for word in $@
do
  arguments="$word $arguments"
done
echo $arguments

when i run this e.g. sh tutorial hello bye
I get the result: bye hello
I need the result to be:

bye
hello

Any ideas anyone?!

Hi,

Try this one,

echo ${argument}|sed 's/ /\n/'

Cheers,
Ranga:)

Hi,

This only works for two arguments given (hello bye), how will i get it working for X amount of arguments given?

echo ${argument}|sed 's/ /\n/g'

g modifier for global substitution.

Cheers,
Ranga:)

One way to display the arguments in reverse order: Tested in ksh not bash.

#Takes in the arguments and displays them in reverse order
if [ $# -eq 0 ]
then
       echo "No arguments entered in script $0, try again"
       exit 1
fi
max=$#
counter=$max
while [ ${counter} -ge 1 ]
do
        eval arg=\$${counter}
        echo "Argument number ${counter} : ${arg}"
        counter=$(( ${counter} - 1 ))
done

./scriptname a b c
Argument number 3 : c
Argument number 2 : b
Argument number 1 : a

Another way:

echo $@ | awk '{for(i=0;i<NF;i++) {print $(NF-i)}}'

@jawsnn
Ingenious for normal script calls, but what if any of the parameters contains one or more space characters?
(This came up yesterday in another post).

arguments=""
for word
do
  arguments="$word
$arguments"
done
printf "%s" "$arguments"