How to preserve line breaks when storing command output to a variable?

前端 未结 2 1626
無奈伤痛
無奈伤痛 2020-11-29 19:58

I’m using bash shell on Linux. I have this simple script …

#!/bin/bash

TEMP=`sed -n \'/\'\"Starting deployment of\"\'/,/\'\"Failed to start context\"\'/p\'         


        
相关标签:
2条回答
  • 2020-11-29 20:14

    I have ran into the same problem, a quote will help

    ubuntu@host:~/apps$ apps="abc
    > def"
    ubuntu@host:~/apps$ echo $apps
    abc def
    ubuntu@host:~/apps$ echo "$apps"
    abc
    def
    
    0 讨论(0)
  • 2020-11-29 20:25

    Quote your variables. Here is it why:

    $ f="fafafda
    > adffd
    > adfadf
    > adfafd
    > afd"
    

    $ echo $f
    fafafda adffd adfadf adfafd afd
    

    $ echo "$f"
    fafafda
    adffd
    adfadf
    adfafd
    afd
    

    Without quotes, the shell replaces $TEMP with the characters it contains (one of which is a newline). Then, before invoking echo shell splits that string into multiple arguments using the Internal Field Separator (IFS), and passes that resulting list of arguments to echo. By default, the IFS is set to whitespace (spaces, tabs, and newlines), so the shell chops your $TEMP string into arguments and it never gets to see the newline, because the shell considers it a separator, just like a space.

    0 讨论(0)
提交回复
热议问题