Bash: Variable in single quote

后端 未结 3 944
逝去的感伤
逝去的感伤 2020-12-11 07:35

First take a look at this question: Bash or GoogleCL: new line in a string parameter

I want to add a variable ${date} into the \"summary\" now:

googl         


        
相关标签:
3条回答
  • 2020-12-11 08:03

    Variables are not expanded within single quotes. Either you can do like William suggests, or you can rewrite the line into double quotes, which will expand the variable as you want.

    "Today is ${date}. Poor whiskers takes a tumble.\nShe's fine, though, don't worry."
    

    Bonus: Doing this way you won't have to escape your single quotes.

    Now I read the link, and you say \n won't expand. A workaround for that would be something like this:

    --summary $(echo -e "Today is...")
    

    It's a bit crude to use a subshell for this, but it will save you from backslashing your quotes.

    0 讨论(0)
  • 2020-12-11 08:06

    I'll add yet another option to the list: define a variable as newline, then use that inside double-quotes.

    nl=$'\n'
    ...
       --summary "Today is ${date}. Poor whiskers takes a tumble.${nl}She's fine, though, don't worry."
    
    0 讨论(0)
  • 2020-12-11 08:23

    Rather than attempting to expand a variable inside a single quoted string, the typical solution is to concatenate single and double quoted strings. In other words:

    'Today is'"${date}"'. Poor' ...
    
    0 讨论(0)
提交回复
热议问题