Skip to main content
Tweeted twitter.com/StackUnix/status/1174881249418260480
Became Hot Network Question
edited tags; edited tags
Link
Kusalananda
  • 355.8k
  • 42
  • 735
  • 1.1k
edited title
Link
a.smith
  • 745
  • 4
  • 15
  • 30

Shell BASH script: How to assign each line of command output to values in an array?

added 4 characters in body
Source Link
terdon
  • 252.2k
  • 69
  • 480
  • 718

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

Every time iI run my command, the order changes so iI 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}")

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}")

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}")
Source Link
a.smith
  • 745
  • 4
  • 15
  • 30
Loading