I have to write a script, which will take all arguments and print them in reverse.
I\'ve made a solution, but find it very bad. Do you have a smarter idea?
bash:
#!/bin/bash
for i in "$@"; do
echo "$i"
done | tac
call this script like:
./reverse 1 2 3 4
it will print:
4
3
2
1
Could do this
for (( i=$#;i>0;i-- ));do
echo "${!i}"
done
This uses the below
c style for loop
Parameter indirect expansion
(${!i}
towards the bottom of the page)
And $#
which is the number of arguments to the script
Simply:
#!/bin/sh
o=
for i;do
o="$i $o"
done
echo "$o"
will work as
./rev.sh 1 2 3 4
4 3 2 1
Or
./rev.sh world! Hello
Hello world!
Just replace echo
by printf "%s\n"
:
#!/bin/sh
o=
for i;do
o="$i $o"
done
printf "%s\n" $o
If your argument could contain spaces, you could use bash arrays:
#!/bin/bash
declare -a o=()
for i;do
o=("$i" "${o[@]}")
done
printf "%s\n" "${o[@]}"
Sample:
./rev.sh "Hello world" print will this
this
will
print
Hello world
Portably and POSIXly, without arrays and working with spaces and newlines:
Reverse the positional parameters:
flag=''; c=1; for a in "$@"; do set -- "$a" ${flag-"$@"}; unset flag; done
Print them:
printf '<%s>' "$@"; echo
you can use this one liner:
echo $@ | tr ' ' '\n' | tac | tr '\n' ' '