2

I ran across some bash code during a review that reassigns a variable to itself using echo. The variable is an array. The code basically assigns the variable to itself with `echo $a`.

a=(one two three)
a=`echo $a`

What purpose does this serve?

  • 2
    Ten demerits for whoever wrote that. – chepner Nov 24 '15 at 20:25
2

It trims the first element of the array:

a=( ' one ' two three )
a=$(echo $a)
echo "<$a>"

Output:

<one>

You can play with various combinations of quoting:

#! /bin/bash
for i in {1..4} ; do 
    a=( $' one \n * two ' three four )
    case $i in
        (1) a=$(echo $a)     ;;
        (2) a=$(echo "$a")   ;;
        (3) a="$(echo $a)"   ;;
        (4) a="$(echo "$a")" ;;
    esac
    echo "<$a>"
done

But basically, you should use

a[0]=...

if you want to assign the the first element of an array, and

echo "${a[0]}"

if you want to output its first element.

  • 1
    That said, you might as well just use ${a[0]}, which is not only easier to read, but doesn't suffer from some of the problems present in this method (word splitting, globbing, etc). – Chris Down Nov 24 '15 at 17:43

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.