当存储在变量中时,subshell的括号不起作用 [英] Parentheses for subshell don't work when stored in a variable
问题描述
命令:
( echo 1 )
当我在命令行中输入它时,它工作正常,但是如果将其存储为变量并调用它,则会出现错误:
works fine when I input it in the command line but if I store it as a variable and call it, it gives the error:
(echo: command not found
代码:
input="( echo 1 )"
$input
为什么当我这样称呼括号时,它不以相同的方式评估括号并将其放入子壳中?
Why doesn't it evaluate the parentheses the same way and put it into a subshell when I call it this way?
推荐答案
这在 BashFAQ中进行了详细讨论. #50 .
无引号的扩展仅经历两个阶段的shell解析:字段拆分和全局扩展.因此,首先将( echo 1 )
分为以下几个字段:(
,echo
,1
和)
;每个扩展为一个全局扩展(模拟,因为它们都不是全局扩展);然后它们作为命令运行:(
被调用,第一个参数echo
,第二个参数1
和第三个参数)
.
An unquoted expansion goes through only two stages of shell parsing: Field-splitting, and glob expansion. Thus, ( echo 1 )
is first split into fields: (
, echo
, 1
, and )
; each is expanded as a glob (moot, as none of them are glob expansions); and then they're run as a command: (
is invoked, with the first argument echo
, the second argument 1
, and the third argument )
.
正确存储代码的方法是在函数中
The Right Way to store code is in a function:
# best-practices approach
input() ( echo 1; )
input
...或者,如果您想让人类读者更明确地看到,您真的想要一个子shell,并且不使用括号而不是出于错误或习惯而大括号:
...or, if you want to make it more explicit to a human reader that you really want a subshell and weren't using parens rather than braces by error or habit:
# same, but more explicit about intent
input() { (echo 1); }
input
...如果不可能的话,可以使用eval
(但请注意 Bash常见问题#48 ):
...if not possible, one can use eval
(but be wary of the caveats given in BashFAQ #48):
# avoid this approach if at all possible
input="( echo 1 )"
eval "$input"
如果要在字符串中构建命令的真正原因是要参数化其内容,请改用数组:
If the real reason you're building a command in a string is to parameterize its contents, use an array instead:
input_args=( 1 ) # define an array
input() ( echo "${input_args[@]}" ) # use that array in a function (if needed)
# add things according to conditional logic as appropriate
if (( 2 > 1 )); then
input_args+=( "possible argument here" )
fi
# call the function, or just use the array directly, such as: (echo "$(input_args[@]}" )
input
这篇关于当存储在变量中时,subshell的括号不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!