Bash Script – Assign Command Output Lines to Array Values

arraybashshell-script

When running a command, I get 10 lines of output. I want to take lines 2-4-6-8-10 and put them into an array.

Every time I run my command, the order changes so I need to do this in one go. I had tried running my command and picking out line 2, then running again and picking out line 4 etc., but because the order changes this does not work:

value1=$(my_command |sed '2q;d')
value2=$(my_command |sed '4q;d')
value3=$(my_command |sed '6q;d')
value4=$(my_command |sed '8q;d')
value5=$(my_command |sed '10q;d')

MY_ARRAY=("${value1}" "${value2}" "${value3}" "${value4}" "${value5}")

Best Answer

Using readarray in the bash shell, and GNU sed:

readarray -t my_array < <( my_command | sed '1~2d' )

The built-in readarray reads the lines into an array. The lines are read from a process substitution. The sed command in the process substitution will only output every second line read from my_command (and could also be written sed '1!n;d', or as sed -n 'n;p' with standard sed).

In GNU sed, the address n~m addresses every m:th line starting at line n. This is a GNU extension to standard sed, for convenience.

The my_command command will only ever be called once.

Testing:

$ readarray -t my_array < <( seq 10 | sed '1~2d' )
$ printf '%s\n' "${my_array[@]}"
2
4
6
8
10
Related Question