在bash shell脚本单引号内变量的扩张命令 [英] Expansion of variable inside single quotes in a command in bash shell script

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

问题描述

我想从的的bash shell脚本运行命令的有单引号和其他一些命令的单引号和一个变量。

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

例如。 回购FORALL -c'.... $变量

在这种格式,$转义和可变未展开。

In this format, $ is escaped and 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

推荐答案

在单引号一切都无一例外preserved。你甚至无法逃避单引号。

Inside single quotes everything is preserved without exception. You can't even escape single quotes.

这意味着你要关闭报价,插入一些东西,然后重新输入一遍。

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

'before'"$variable"'after'

'before'\''after'

'before'"'"'after'

正如你可以验证,上述各行的每一个人只是一个字的外壳。字符串连接简单地并列进行。行情指示之类的东西或空格(非分裂)不同变量间pretation的需要。对于引用的一个很好的教程,也看到马克里德的回答。

As you can verify, every one of the above lines is just a single word to the shell. String concatenation is simply done by juxtaposition. Quotes indicate the need for different interpretation of things like whitespace or (non-splitting) variables. For a good tutorial of quoting, also see Mark Reed's answer.

请注意,你应该在程序连接字符串和变量避免建筑shell命令。这是类似于大多数编程语言,或建筑物的SQL请求(SQL注入!)使用评估一个坏主意。

Note that you should avoid building shell commands by procedurally concatenating strings and variables. This is a bad idea similar to using eval in most programming languages, or building SQL requests (SQL injection!).

一般是可能的有在命令占位符,并与变量一起提供的命令,以使被叫方可以以安全的方式替换占位符,代替主叫用户连接字符串,由此混合code和数据

Usually it is possible to have placeholders in the command, and to supply the command together with variables so that the callee can replace the placeholders in a safe way, instead of the caller concatenating strings, thereby mixing code and data.

例如,与在外部壳体的参数运行shell命令:

For example, to run a shell command with an arguments in an external shell:

myvar=foo
/bin/sh -c 'echo "argument 1 is: $1"' -- "$myvar"

在另一方面,以下是非常不安全的。 DO NOT DO THIS

On the other hand, the following is very unsafe. DON'T DO THIS

myvar='foo"; rm -rf /mypreciousdata; echo "you were hacked'  # exploit
/bin/sh -c "echo \"Argument 1 is: $myvar\""

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆