Search code examples
arraysbashloopsreverse

How to print output of a for loop in a single line in Bash


echo -n "input: "
while read line 
do 
   array=("${array[@]}" $line)
done
len=${#array[@]}

echo -n "Output:"
for (( n=0; n<=len; n++ ))
    do 
    echo "${array[n]}" | rev
done 

I want the reversed output to be in a single line.

Gratuitous screen shot


Solution

  • Why aren't you using a reverse loop?

    sep="" # no separator before first entry
    for ((n=len; n>=0; n--))
    do 
        printf "%s%s" "$sep" "${array[n]}"
        sep=" "
    done
    printf '\n'
    

    Generally prefer printf over echo -n, though both would work here.

    Or if you just want the output to be reversed character by character;

    echo "${array[@]}" | rev
    

    But then why do you need an array at all?

    read -r -p 'input: '
    echo "$REPLY" | rev