for loop - reverse reading

All,

Here is my for loop

export CFGLIST="LIST1 LIST2 LIST3"
 
for i in $CFGLIST
do
  echo print $i
done

The output will be

LIST1
LIST2
LIST3

But i want it display

LIST3
LIST2
LIST1

Can you please help me how to read in reverse order?

Thanks
Bala

 
a="LIST1 LIST2 LIST3"
$ echo $a | nawk '{for(i=NF;i>=1;i--){print $i}}'
LIST3
LIST2
LIST1

#!/bin/bash

CFGLIST=(LIST1 LIST2 LIST3)
i=${#CFGLIST
[*]}
((i-=1))
while [ $i -ge 0 ]
do
  echo ${CFGLIST[$i]}
  ((i-=1))
done

--ahamed

kamaraj, i'm finding difficulty without nawk - Thanks

Ahamed - if i have as below

CFGLIST=("LIST1 LIST2 LIST3") - It returns same value

Can you please help?

Thanks
Bala

use awk instead of nawk

---------- Post updated at 05:54 PM ---------- Previous update was at 05:49 PM ----------

 
$ echo $CFGLIST | perl -lane 'print join(" ",reverse @F)' 
LIST3 LIST2 LIST1

A simple Shell method:

export CFGLIST="LIST1 LIST2 LIST3"
set ${CFGLIST}
echo "$3"
echo "$2"
echo "$1"

./scriptname
LIST3
LIST2
LIST1
export CFGLIST="LIST1 LIST2 LIST3"

revlist=
for i in $CFGLIST
do
  revlist="$i $revlist"
done

for i in $revlist
do
  echo "print $i"
done

A more complicated Shell method for any number of items:

export CFGLIST="LIST1 LIST2 LIST3"
set ${CFGLIST}
items=$#
counter=$items
while [ $counter -ne 0 ]
do
        eval output=\$${counter}
        echo "${output}"
        counter=$((${counter} - 1))
done

./scriptname
LIST3
LIST2
LIST1

Just for the fun of it since there are 18 ways to do most tasks (some better than others), how about using an array (ksh93 on solaris)?

#!/usr/dt/bin/dtksh

export CFGLIST="LIST1 LIST2 LIST3"

# Turn it into an array
set -A CFGLIST $CFGLIST

# Array is zero-based so start one less than the number of elements.
for (( i=$((${#CFGLIST
[*]}-1));i>=0;i-- ))
do
  print "Array element ${i}: ${CFGLIST[${i}]}"
done

exit 0

Output:

$ efs
Array element 2: LIST3
Array element 1: LIST2
Array element 0: LIST1
$