BASH assigning command output into an array

Often find myself needing to do this but never remember how…

# flirble=(`ls -ltr ssh* | tail -3 | tr -s ' ' | cut -d ' ' -f 9` )
# echo ${flirble[*]}
ssh_host_key ssh_host_dsa_key.pub ssh_host_dsa_key
# echo ${flirble[0]}
ssh_host_key
# echo ${flirble[1]}
ssh_host_dsa_key.pub
# echo ${flirble[2]}
ssh_host_dsa_key
# echo ${flirble[3]}
# ls -ltr ssh* | tail -3
-rw-------  1 robin cm-users 539 Aug 11 12:40 ssh_host_key
-rw-r--r--  1 robin cm-users 614 Aug 11 12:40 ssh_host_dsa_key.pub
-rw-------  1 robin cm-users 668 Aug 11 12:40 ssh_host_dsa_key

This and more useful array manipulation can be found in Chapter 26 of the Advanced Bash Scripting Guide.


2 Comments

  1. r3d says:

    A little comment

    ls -1rt would not have been simpler than a command with 3 pipes?
    -1 list one file on each line

  2. robin says:

    Sure! I dont know what I was thinking when I wrote that example! The main thing I wanted to post about (and hence be able to find next time I forgot the syntax) was that flirble=(“) would populate the array flirble with the output of . I should have used a saner example though!

Leave a Reply