How do you retain trailing newlines when storing command output in a variable?

前端 未结 1 1829
盖世英雄少女心
盖世英雄少女心 2021-01-24 17:21

Is it possible to retain trailing newlines when storing the output of a command in a variable?

$ echo \"foo
\" # newline appears after foo
foo

$ MYVAR=\"$(echo          


        
相关标签:
1条回答
  • 2021-01-24 18:06

    You can add a sentinel to the end of the stream:

    $ my_var=$'foo\n\n'
    $ captured=$( echo -n "$my_var"; echo -n "x" )
    

    which you then remove:

    $ captured=${captured%x}
    $ echo "$captured"
    
    0 讨论(0)
提交回复
热议问题