Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split command output into array of lines

Tags:

bash

Here's my bash function to get a command's output as parameter and then return an array of output lines.

function get_lines { 
    while read -r line; do 
        echo $line
    done <<< $1
}

SESSIONS=`loginctl list-sessions`
get_lines "$SESSIONS"

Actual output of loginctl list-sessions is:

   SESSION        UID USER             SEAT            
        c2       1000 asif             seat0           
        c7       1002 sadia            seat0           

But the while loop only runs once printing all output in a single line. How can I get an array of lines and return it?

like image 896
8thperson Avatar asked May 26 '26 16:05

8thperson


1 Answers

You could use readarray and avoid the get_lines function:

readarray SESSIONS < <(loginctl --no-legend list-sessions)

this create the array SESSIONS with each line of the output of the command mapped to an element of the array.

like image 168
andy Avatar answered May 30 '26 04:05

andy