如何在 bash 中回显包含未转义美元符号的变量

发布于 2024-09-27 03:16:42 字数 256 浏览 0 评论 0原文

如果我有一个包含未转义的美元符号的变量,有什么方法可以回显该变量的全部内容吗?

例如,有东西调用脚本:

./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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

﹏雨一样淡蓝的深情 2024-10-04 03:16:42

问题是脚本首先接收“test1”,并且它不可能知道存在对空(未声明)变量的引用。在将 $ 传递给脚本之前,您必须对其进行转义,如下所示:

./script.sh "test1\$test2"

或者使用单引号 ' 如下:

./script.sh 'test1$test2'

在这种情况下,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:

./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.

坐在坟头思考人生 2024-10-04 03:16:42

该变量在脚本运行之前被替换。

./script.sh 'test1$test2'

The variable is replaced before the script is run.

./script.sh 'test1$test2'
傾旎 2024-10-04 03:16:42

通过使用单引号,像 $ 这样的元字符将保留其字面值。如果使用双引号,变量名称将被插入。

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

夜未央樱花落 2024-10-04 03:16:42

正如 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 your echo "${1}". This is a good practice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文