Capturing multiple line output into a Bash variable

后端 未结 7 2151
忘掉有多难
忘掉有多难 2020-11-22 03:17

I\'ve got a script \'myscript\' that outputs the following:

abc
def
ghi

in another script, I call:

declare RESULT=$(./myscr         


        
7条回答
  •  灰色年华
    2020-11-22 03:45

    Parsing multiple output

    Introduction

    So your myscript output 3 lines, could look like:

    myscript() { echo $'abc\ndef\nghi'; }
    

    or

    myscript() { local i; for i in abc def ghi ;do echo $i; done ;}
    

    Ok this is a function, not a script (no need of path ./), but output is same

    myscript
    abc
    def
    ghi
    

    Considering result code

    To check for result code, test function will become:

    myscript() { local i;for i in abc def ghi ;do echo $i;done;return $((RANDOM%128));}
    

    1. Storing multiple output in one single variable, showing newlines

    Your operation is correct:

    RESULT=$(myscript)
    

    About result code, you could add:

    RCODE=$?
    

    even in same line:

    RESULT=$(myscript) RCODE=$?
    

    Then

    echo $RESULT 
    abc def ghi
    
    echo "$RESULT"
    abc
    def
    ghi
    
    echo ${RESULT@Q}
    $'abc\ndef\nghi'
    
    printf "%q\n" "$RESULT"
    $'abc\ndef\nghi'
    

    but for showing variable definition, use declare -p:

    declare -p RESULT
    declare -- RESULT="abc
    def
    ghi"
    

    2. Parsing multiple output in array, using mapfile

    Storing answer into myvar variable:

    mapfile -t myvar < <(myscript)
    echo ${myvar[2]}
    ghi
    

    Showing $myvar:

    declare -p myvar
    declare -a myvar=([0]="abc" [1]="def" [2]="ghi")
    

    Considering result code

    In case you have to check for result code, you could:

    RESULT=$(myscript) RCODE=$?
    mapfile -t myvar <<<"$RESULT"
    

    3. Parsing multiple output by consecutives read in command group

    { read firstline; read secondline; read thirdline;} < <(myscript)
    echo $secondline
    def
    

    Showing variables:

    declare -p firstline secondline thirdline
    declare -- firstline="abc"
    declare -- secondline="def"
    declare -- thirdline="ghi"
    

    I often use:

    { read foo;read foo total use free foo ;} < <(df -k /)
    

    Then

    declare -p use free total
    declare -- use="843476"
    declare -- free="582128"
    declare -- total="1515376"
    

    Considering result code

    Same prepended step:

    RESULT=$(myscript) RCODE=$?
    { read firstline; read secondline; read thirdline;} <<<"$RESULT"
    
    declare -p firstline secondline thirdline RCODE
    declare -- firstline="abc"
    declare -- secondline="def"
    declare -- thirdline="ghi"
    declare -- RCODE="50"
    

提交回复
热议问题