在Bash中的命令中单引号内的变量扩展

在Bash中的命令中单引号内的变量扩展

本文介绍了在Bash中的命令中单引号内的变量扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 bash脚本运行一个命令,该脚本中有单引号,在单引号内还有一些其他命令以及一个变量.

I want to run a command from a bash script which has single quotes and some other commands inside the single quotes and a variable.

例如repo forall -c '....$variable'

以这种格式,$被转义,并且变量未展开.

In this format, $ is escaped and the variable is not expanded.

我尝试了以下变体,但被拒绝了:

I tried the following variations but they were rejected:

repo forall -c '...."$variable" '

repo forall -c " '....$variable' "

" repo forall -c '....$variable' "

repo forall -c "'" ....$variable "'"

如果我用值代替变量,则命令执行得很好.

If I substitute the value in place of the variable the command is executed just fine.

请告诉我我要去哪里错了.

Please tell me where am I going wrong.

推荐答案

在单引号内,所有内容均按原样保留,无一例外.

Inside single quotes everything is preserved literally, without exception.

这意味着您必须关闭引号,插入一些内容,然后再次重新输入.

That means you have to close the quotes, insert something, and then re-enter again.

'before'"$variable"'after'
'before'"'"'after'
'before'\''after'

单词串联仅通过并置即可完成.正如您可以验证的那样,以上每一行对shell来说都是一个单词.引号(单引号或双引号,视情况而定)不会隔离单词.它们仅用于禁用对各种特殊字符的解释,例如空格,$;....有关引用的良好教程,请参见Mark Reed的答案.同样相关:哪个字符需要以bash进行转义吗?

Word concatenation is simply done by juxtaposition. As you can verify, each of the above lines is a single word to the shell. Quotes (single or double quotes, depending on the situation) don't isolate words. They are only used to disable interpretation of various special characters, like whitespace, $, ;... For a good tutorial on quoting see Mark Reed's answer. Also relevant: Which characters need to be escaped in bash?

您应该绝对避免通过连接变量来构建Shell命令.这是一个糟糕的主意,类似于串联SQL片段(SQL注入!).

You should absolutely avoid building shell commands by concatenating variables. This is a bad idea similar to concatenation of SQL fragments (SQL injection!).

通常可以在命令中使用占位符,并将命令与变量一起提供,以便被调用者可以从调用参数列表中接收它们.

Usually it is possible to have placeholders in the command, and to supply the command together with variables so that the callee can receive them from the invocation arguments list.

例如,以下内容非常不安全.不要这样做

For example, the following is very unsafe. DON'T DO THIS

script="echo \"Argument 1 is: $myvar\""
/bin/sh -c "$script"

如果$myvar的内容不受信任,则可以利用以下漏洞:

If the contents of $myvar is untrusted, here is an exploit:

myvar='foo"; echo "you were hacked'

使用位置参数代替上面的调用.以下调用会更好-不能被利用:

Instead of the above invocation, use positional arguments. The following invocation is better -- it's not exploitable:

script='echo "arg 1 is: $1"'
/bin/sh -c "$script" -- "$myvar"

请注意,在script的赋值中使用了单个刻度,这意味着它是按字面意思进行的,没有变量扩展或任何其他形式的解释.

Note the use of single ticks in the assignment to script, which means that it's taken literally, without variable expansion or any other form of interpretation.

这篇关于在Bash中的命令中单引号内的变量扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:22