如何在 bash 中回显包含未转义美元符号的变量
如果我有一个包含未转义的美元符号的变量,有什么方法可以回显该变量的全部内容吗?
例如,有东西调用脚本:
./script.sh "test1$test2"
然后,如果我想使用该参数,它会被“截断”,如下所示:
echo ${1}< br> test1
当然,单引号变量名称没有帮助。我不知道如何引用它,以便在脚本收到参数后我至少可以自己转义美元符号。
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"
and then if I want to use the parameter it gets "truncated" like so:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是脚本首先接收“test1”,并且它不可能知道存在对空(未声明)变量的引用。在将
$
传递给脚本之前,您必须对其进行转义,如下所示:或者使用单引号
'
如下:在这种情况下,bash 不会扩展该参数字符串中的变量。
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:Or use single quotes
'
like this:In which case bash will not expand variables from that parameter string.
该变量在脚本运行之前被替换。
The variable is replaced before the script is run.
通过使用单引号,像
$
这样的元字符将保留其字面值。如果使用双引号,变量名称将被插入。by using single quotes , meta characters like
$
will retain its literal value. If double quotes are used, variable names will get interpolated.正如 Ignacio 告诉您的那样,变量被替换,因此您的脚本将
./script.sh test1
作为$0
和$1
的值。但即使在您使用文字引号来传递参数的情况下,您也应该始终在
echo "${1}"
中引用"$1"
。这是一个很好的做法。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 yourecho "${1}"
. This is a good practice.