bash 如何在bash中回显包含未转义美元符号的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3923623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to echo a variable containing an unescaped dollar sign in bash
提问by Not22
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:
例如某事调用脚本:
./script.sh "test1$test2"
./script.sh "test1$test2"
and then if I want to use the parameter it gets "truncated" like so:
然后,如果我想使用该参数,它会像这样被“截断”:
echo ${1}
test1
echo ${1}
test1
Of course single-quoting the varaible name doesn't help. I can't figure out how to quote it so that I can at least escape the dollar sign myself once the script recieves the parameter.
当然,单引号变量名无济于事。我不知道如何引用它,以便我至少可以在脚本收到参数后自己转义美元符号。
采纳答案by Ignacio Vazquez-Abrams
The variable is replaced before the script is run.
在脚本运行之前替换变量。
./script.sh 'test1$test2'
回答by
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:
问题是脚本首先接收“test1”,它不可能知道存在对空(未声明)变量的引用。您必须$
在将其传递给脚本之前转义,如下所示:
./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.
在这种情况下,bash 不会从该参数字符串中扩展变量。
回答by ghostdog74
by using single quotes , meta characters like $
will retain its literal value. If double quotes are used, variable names will get interpolated.
通过使用单引号,元字符 like$
将保留其文字值。如果使用双引号,变量名将被插入。
回答by Benoit
As Ignacio told you, the variable is replaced, so your scripts gets ./script.sh test1
as values for $0
and $1
.
正如 Ignacio 告诉您的那样,该变量已被替换,因此您的脚本将./script.sh test1
作为$0
和 的值$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.
但即使在您使用文字引号传递参数的情况下,您也应该始终"$1"
在echo "${1}"
. 这是一个很好的做法。