Search code examples
shell

How does y=$x""$y perform reverse


I used this code for reversing command line arguments that are in $@ my code is

#!/bin/sh
if [ $# -eq 0 ]
then
    echo "enter a valid argument" 
    exit
fi
for x in $@
do
    y=$x""$y
done
echo "the reverse is :$y"

I am unable to understand how this works. Can anyone help me?


Solution

  • $@ takes all parameters, space separated (won't work right if the parameters contain spaces, use "$@" for that). Then the for loop takes the variable y, which starts empty, and puts the current parameter x in front of it: y=$x""$y. So if I have parameters a b c, then y=a ... y="b a" ... y="c b a"