简体   繁体   English

在bash中将变量扩展为命令的一部分

[英]Expand variables as part of a command in bash

Is there any way to expand variables inside commands? 有什么方法可以在命令内部扩展变量? It's hard for me to explain what I want to achieve, so I'll demonstrate it: 我很难解释我想要达到的目标,因此我将演示它:

Let's say I have this construct: 假设我有这个结构:

var1="\${var2} -eq 7"

if [ ${var1} ]; do....

And the desired output is: 所需的输出是:

if [ ${var2} -eq 7 ]; do....

Now obviously that doesn't work, but how would I make something like this work? 现在显然这是行不通的,但是我将如何进行类似的工作?

You should use functions for this sort of thing. 您应该对此类事情使用函数。 You can also use eval , but please don't. 您也可以使用eval ,但请不要使用。

$ equalsSeven() (($1 == 7))
$ if equalsSeven 7; then echo Presto; fi
Presto

man bash , /Compound man bash /Compound

For that, is evil eval : 为此, eval是邪恶的:

var1="\${var2} -eq 7"
var2=7
if eval [ ${var1} ]; then
    echo var2 is 7
fi

Note that if ...; do 注意, if ...; do if ...; do is invalid, after the if expression comes then , not do . if ...; do无效, if表达式出现then ,则not do

Since bash's numerical evaluation does actually expand variables (and, as a bonus, doesn't require them to be signaled with a $ ) you can achieve this in bash quite easily: 由于bash的数值评估实际上确实扩展了变量(并且,作为奖励,不需要用$表示信号),因此可以在bash中轻松实现此目的:

$ comparison='x==7'
$ x=7
$ if ((comparison)); then echo yup; else echo nope; fi
yup
$ x=8
$ if ((comparison)); then echo yup; else echo nope; fi
nope

This works because ((…)) and $((…)) are numerical contexts. 之所以可行,是因为((…))$((…))是数字上下文。 So is the index of an array, and assignment to a variable declared as numeric. 数组的索引以及声明为数值的变量的分配也是如此。 (However, this feature is almost as evil as eval . Avoid numeric evaluation of unchecked input.) (但是,此功能几乎与eval一样邪恶。请避免对未经检查的输入进行数字求值。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM