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

梦想与她 提交于 2019-11-27 15:01:15

The variable is replaced before the script is run.

./script.sh 'test1$test2'

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!