Thursday, 11 May 2017

Print array elements on separate lines in Bash?



How do I print the array element of a Bash array on separate lines? This one works, but surely there is a better way:




$ my_array=(one two three)
$ for i in ${my_array[@]}; do echo $i; done
one
two
three


Tried this one but it did not work:



$ IFS=$'\n' echo ${my_array[*]}

one two three

Answer



Try doing this :



$ printf '%s\n' "${my_array[@]}"


The difference between $@ and $*:





  • Unquoted, the results are unspecified. In Bash, both expand to separate args
    and then wordsplit and globbed.


  • Quoted, "$@" expands each element as a separate argument, while "$*"
    expands to the args merged into one argument: "$1c$2c..." (where c is
    the first char of IFS).




You almost always want "$@". Same goes for "${arr[@]}".




Always quote them!


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...