Hi all,
I needed help in writing a script for the following question.please help.
Non-recursive shell script that accepts any number of arguments and prints
them in the Reverse order. (For example, if the script is named rargs, then
executing rargs A B C should produce C B A on the standard output).
Thanks
era
June 11, 2008, 8:56am
2
Why can't we use recursion?
#!/bin/sh
case $# in
0|1) echo "$@";;
*) arg=$1; shift; exec "$0" "$@" "$arg"
esac
era
June 12, 2008, 2:58am
3
... Actually that's pretty broken, but you get the idea (-:
joeyg
June 12, 2008, 8:56am
4
Without any recursive programming was an interesting twist. But, I figured there had to be "some" reason for this requirement.
Anyway, I assumed by print in reverse order you meant the reverse of entry order. Saying that, perhaps the following script:
#! /bin/bash
#shift_input
tmp_file="shift_value_temp"
tmp_file2="shift_value_temp2"
tmp_file3="shift_value_temp3"
tmp_file4="shift_value_temp4"
rm $tmp_file 2>/dev/null
rm $tmp_file2 2>/dev/null
rm $tmp_file3 2>/dev/null
rm $tmp_file4 2>/dev/null
echo "$*" >$tmp_file
cat $tmp_file | tr " " "\n" >$tmp_file2
tac $tmp_file2 >$tmp_file3
cat $tmp_file3 | tr "\n" " ">$tmp_file4
cat $tmp_file4
echo " "
> shift_input a b c g h i d e f
f e d i h g c b a
>
Perhaps could be done without the four work files, but I needed to write the data somewhere as I thought about the steps.
Here's one in bash
while [ $# -gt 0 ]
do
rev="$1 $rev"
shift
done
echo $rev
and in Perl
while(@ARGV)
{
unshift @rev, shift @ARGV;
}
print join ' ', @rev, "\n";
era
June 13, 2008, 4:52am
6
For the Perl version, you can just say reverse @ARGV -- no need to code the loop by hand.
#!/bin/sh
exec perl -le '$, = " "; print reverse @ARGV' "$@"
By manipulating $, you can avoid the explicit join.
joeyg's orgy in temp files and Useless Use of Cat (no offense ...) can be simplified radically:
echo "$@" | tr -s " \t" "\n" | tac | tr "\n" " "
If your tr doesn't grok \t and \n you will have to use octal codes or literal tabs and newlines.