3

I want a Unix script which will take multiple column numbers from the user and reverse the contents.

declare -a param="$@"
# enter 0 when exit the insert element
echo "Enter the numbers"
read n
while [ $n -ne 0 ]
do
    x[$i]=`expr $n`
    read n
    let i++
done

#display the all array elements
echo "Array values ${x[@]}"
echo "Array values ${x[*]}"

# To find the array length
length=${#x[*]}
echo $length
  • 2
    Please include an example of your input data and desired output. – terdon Mar 23 '14 at 17:08
5

A copy and paste of my answer to an extremely similar question on stack overflow, which was posted alongside an extremely similar answer to Gnouc's above...

_arr+=( '"${_arrev} is an actual "${array[@]}"' )
_arr+=( '"${_arrev} is created as a result"' )
_arr+=( '"of reversing the key order in"' )
_arr+=( '"this "${_arr}. It handles zsh and"' )
_arr+=( '"bash arrays intelligently by tracking"' )
_arr+=( '"shell "$ENV." quotes=fine ( i hope ) "' )

. <<REVERSE /dev/stdin                    ⏎
    _arrev=( $(: $((l=${#_arr[@]}${ZSH_VERSION++1})) ; printf '"${_arr[$(('$l'-%d))]}" ' `seq 1 $l`) )
REVERSE

echo ; printf %s\\n ${_arrev}

"shell "$ENV." quotes=fine ( i hope ) "
"bash arrays intelligently by tracking"
"this "${_arr}. It handles zsh and"
"of reversing the key order in"
"${_arrev} is created as a result"
"${_arrev} is an actual "${array[@]}"

This should handle any possible array, I think.

If you're interested in what's going on up there, I suggest you have a look here first. Then maybe here, definitely here, and, if you've got the time, here and here.

In all of those answers I discuss different aspects of the here-document (and in many others) which you can use to your advantage. For instance I discuss twice-evaluating variables, which is done above, and in one declare a function that globally declares another function named "_$1" in just 5 or 6 lines - most of which were _$1() { func body ; }. It's pretty handy if you use it correctly.

Regarding the auto-switch between bash/zsh, well that's something else, but very simple as well. See here.

So basically if you can create a bash/zsh, array you should be able to reverse it using only the 3 . <<...REVERSE lines. It does not need to loop over the array in the way a for loop does.

2

If I understand right, you want to reverse contents of an array. You can do it with for loop:

for ((idx=${#x[@]}-1; idx >= 0; idx--))
do
  printf '%s ' "${x[idx]}"
done
  • This drops the last element in a zsh array. – mikeserv Mar 23 '14 at 20:01
  • @mikeserv: The script even doesn't work with zsh. I think OP only want bash. – cuonglm Mar 24 '14 at 1:28
  • In case someone wants to use the same couple of lines more than once. – mikeserv Mar 24 '14 at 1:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.