How to echo a variable containing an unescaped dollar sign in bash

后端 未结 4 1693
攒了一身酷
攒了一身酷 2020-12-01 21:16

If I have a variable containing an unescaped dollar sign, is there any way I can echo the entire contents of the variable?

For example something calls a script:

相关标签:
4条回答
  • 2020-12-01 21:22

    The variable is replaced before the script is run.

    ./script.sh 'test1$test2'
    
    0 讨论(0)
  • 2020-12-01 21:23

    As Ignacio told you, the variable is replaced, so your scripts gets ./script.sh test1 as values for $0 and $1.

    But even in the case you had used literal quotes to pass the argument, you shoudl always quote "$1" in your echo "${1}". This is a good practice.

    0 讨论(0)
  • 2020-12-01 21:32

    by using single quotes , meta characters like $ will retain its literal value. If double quotes are used, variable names will get interpolated.

    0 讨论(0)
  • 2020-12-01 21:33

    The problem is that script receives "test1" in the first place and it cannot possibly know that there was a reference to an empty (undeclared) variable. You have to escape the $ before passing it to the script, like this:

    ./script.sh "test1\$test2"
    

    Or use single quotes ' like this:

    ./script.sh 'test1$test2'
    

    In which case bash will not expand variables from that parameter string.

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