B. Wayne B. Wayne - 1 month ago 14
Bash Question

How do i print arguments in reverse order in shell script?

I was trying to write a script that print the arguments in reverse order.
So if I type bash reverse.sh one two three
I expect my output to be three two one
How can i do this?
This is what I tried and it obviously didn't work...

#!/bin/bash
i=0
a="$"
for word in $*; do
echo $a$(($#-i))
i=$((i+1))
done


This is the output i get

$3
$2
$1


I thought this would print the parameters in order 3, 2, 1 but it didn't. How should I do it? Any help will be much appreciated. Thank you.

Answer

You need eval with echo i.e. you need to evaluate the expansion, not output it:

eval echo $a$(($#-i))

Note that, using eval in general is discouraged as this could result in security implications if the input string is not sanitized. Check John1024's answer to see how this can be done without eval.