Printing array elements in reverse

Hello Experts,

I am trying to print an array in reverse.

Input :

  1. Number of array elements
  2. The array.

Eg:

4
1 2 3 4

Expected Output (elements separated by a space) :

4 3 2 1 

My Code :

read n;
for (( i=$(( $n-1 )); i>=0; i-- )); do
echo "${arr}"
done

However, this is not solving the problem.

Could you please help.

Thanks,
Haider

It works here with slight adjustments using bash:

#!/bin/bash

arr=( 1 2 3 4 )
n=${#arr
[*]}

for (( i = n-1; i >= 0; i-- ))
do
    echo ${arr}
done

Output:

4
3
2
1

---------- Post updated at 09:50 ---------- Previous update was at 09:49 ----------

And if you need all elements on a single line:

...
for (( i = n-1; i >= 0; i-- ))
do
    echo -n "${arr} "
done
echo

remove $

read n;
for (( i=$((n-1)); i>=0; i-- )); do
echo "${arr}"
done

Hello H squared,

Please use code tags as per forum rules for commands/Inputs/codes you are using into your posts. If you have an Input_file and you want to print all the lines into reverse order then following may help you in same.

awk '{num=split($0, A," ");for(i=num;i>=1;i--){Q=Q?Q OFS $i:$i};print Q;Q=""}'   Input_file

EDIT: We could following solutions too.

perl -ne 'chomp;print scalar reverse . "\n";'  Input_file

You could use rev if you have it in your box as follows.

echo "1 2 3 4" | rev
OR
rev Input_file

EDIT2: If you want to print reverse array's elements reverse format into shell and into one line then following may help you in same too.

#!/bin/bash
arr=( 1 2 3 4 )
n=${#arr
[*]}
for (( i = n-1; i >= 0; i-- )); do     Q="$Q ${arr}"; done
echo $Q
  
OR
  
#!/bin/bash
arr=( 1 2 3 4 )
n=${#arr
[*]}
for (( i = n-1; i >= 0; i-- ))
do
     Q="$Q ${arr}"
done
echo $Q

Thanks,
R. Singh

1 Like

The destructive way:

$ echo ${munchy[@]}
data test my is this there hello
$ while [[ ${#munchy[@]} > 0 ]]
> do
> echo ${munchy[-1]}
> unset munchy[-1]
> done
hello
there
this
is
my
test
data

This works for bash 4, which allows negative indices to count from the right. For earlier versions of bash, replace munchy[-1] with munchy[${#munchy[@]}-1]

If you've the rev utility installed, then you could also do:

echo "1 2 3 4" | rev

Note that it's not portable though.

Hi.

Portable, assuming perl is available:

perl -w -e 'print join(" ", reverse @ARGV),"\n";' $VAR

as in:

VAR="Now is the time"
perl -w -e 'print join(" ", reverse @ARGV),"\n";' $VAR

producing:

time the is Now

For a file, one could use:

perl -wn -e '@a=split; print join(" ",reverse @a),"\n";' $FILE

where if the file contains:

Beware the Jubjub bird, and shun
The frumious Bandersnatch!

would produce:

shun and bird, Jubjub the Beware
Bandersnatch! frumious The

Run on a system:

OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution        : Debian 8.4 (jessie) 
bash GNU bash 4.3.30
perl 5.20.2

See man pages, perldoc -f reverse , perldoc perlrun for details.

Best wishes ... cheers, drl