How do I use variables in single quoted strings?

后端 未结 7 2022
既然无缘
既然无缘 2020-11-22 15:40

I am just wondering how I can echo a variable inside single quotes (I am using single quotes as the string has quotation marks in it).

     echo \'test text          


        
相关标签:
7条回答
  • 2020-11-22 15:59

    Use a heredoc:

    cat << EOF >> ${FILE}
    test text "here_is_some_test_text_$counter" "output"
    EOF
    
    0 讨论(0)
  • 2020-11-22 15:59

    with a subshell:

    var='hello' echo 'blah_'`echo $var`' blah blah';
    
    0 讨论(0)
  • 2020-11-22 16:00

    Output a variable wrapped with single quotes:

    printf "'"'Hello %s'"'" world
    
    0 讨论(0)
  • 2020-11-22 16:01

    Variables are expanded in double quoted strings, but not in single quoted strings:

     $ name=World
    
     $ echo "Hello $name"
     Hello World
    
     $ echo 'Hello $name'
     Hello $name
    

    If you can simply switch quotes, do so.

    If you prefer sticking with single quotes to avoid the additional escaping, you can instead mix and match quotes in the same argument:

     $ echo 'single quoted. '"Double quoted. "'Single quoted again.'
     single quoted. Double quoted. Single quoted again.
    
     $ echo '"$name" has the value '"$name"
     "$name" has the value World
    

    Applied to your case:

     echo 'test text "here_is_some_test_text_'"$counter"'" "output"' >> "$FILE"
    
    0 讨论(0)
  • 2020-11-22 16:07

    You can do it this way:

    $ counter=1 eval echo `echo 'test text \
       "here_is_some_test_text_$counter" "output"' | \
       sed -s 's/\"/\\\\"/g'` > file
    
    cat file
    test text "here_is_some_test_text_1" "output"
    

    Explanation: Eval command will process a string as command, so after the correct amount of escaping it will produce the desired result.

    It says execute the following string as command:

    'echo test text \"here_is_some_test_text_$counter\" \"output\"'
    

    Command again in one line:

    counter=1 eval echo `echo 'test text "here_is_some_test_text_$counter" "output"' | sed -s 's/\"/\\\\"/g'` > file
    
    0 讨论(0)
  • 2020-11-22 16:12

    use printf:

    printf 'test text "here_is_some_test_text_%s" "output"\n' "$counter" >> ${FILE}
    
    0 讨论(0)
提交回复
热议问题