Capturing multiple line output into a Bash variable

后端 未结 7 2240
忘掉有多难
忘掉有多难 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:44

    Another pitfall with this is that command substitution — $() — strips trailing newlines. Probably not always important, but if you really want to preserve exactly what was output, you'll have to use another line and some quoting:

    RESULTX="$(./myscript; echo x)"
    RESULT="${RESULTX%x}"
    

    This is especially important if you want to handle all possible filenames (to avoid undefined behavior like operating on the wrong file).

提交回复
热议问题