什么是EVAL / bash的-c点,而不是仅仅评估一个变量? [英] What's the point of eval/bash -c as opposed to just evaluating a variable?

查看:129
本文介绍了什么是EVAL / bash的-c点,而不是仅仅评估一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有存储在一个变量下面的命令:

Suppose you have the following command stored in a variable:

COMMAND='echo hello'

有什么

$ eval "$COMMAND"
hello

$ bash -c "$COMMAND"
hello

$ $COMMAND
hello

?为什么几乎从来没有使用过,如果它是短,(据我可以看到)的最后一个版本做同样的事情?

? Why is the last version almost never used if it is shorter and (as far as I can see) does exactly the same thing?

推荐答案

第三种形式是一点都不像另外两个 - 但是要理解为什么,我们需要进入操作的顺序当bash在跨preting一个命令,看看其中哪些是其次,当每一种方法是在使用中。

The third form is not at all like the other two -- but to understand why, we need to go into the order of operations when bash in interpreting a command, and look at which of those are followed when each method is in use.


  1. 报价处理

  2. 分成命令

  3. 特殊操作解析

  4. 展开

  5. 分词

  6. 通配符

  7. 执行

的eval$字符串如下全部来自#1起以上步骤。因此:


Using eval "$string"

eval "$string" follows all the above steps starting from #1. Thus:


  • 字符串中的文字引号成为句法报价

  • 特种作业人员,如>()处理

  • 展开,如 $ foo的很荣幸

  • 这些扩展的结果上的字符分为空白成单独的词

  • 如果他们解析为相同,并有可用的比赛,最后执行命令这些话被扩展为水珠。

...执行相同评估的做法,但的推出作为一个单独的进程中新的外壳的;因此,改变变量状态,当前目录等,将在这个新的进程退出到期。 (注意,那就是,新的外壳可能是一个不同的跨preTER支持不同的语言;即上海-c富将不支持相同的语法该庆典 KSH 的zsh 等做)

...performs the same as eval does, but in a new shell launched as a separate process; thus, changes to variable state, current directory, etc. will expire when this new process exits. (Note, too, that that new shell may be a different interpreter supporting a different language; ie. sh -c "foo" will not support the same syntax that bash, ksh, zsh, etc. do).

...开始于第5步字拆分。

...starts at step 5, "Word Splitting".

这是什么意思?

的printf'%s的\\ n'两个字从而将解析为的printf %S \\ n ,而不是通常的/预期行为的printf %S \\ n 两个字(带引号由外壳消耗)。

printf '%s\n' "two words" will thus parse as printf %s\n "two words", as opposed to the usual/expected behavior of printf %s\n two words (with the quotes being consumed by the shell).

因此​​:

s='echo foo && echo bar'
$s

...会发出以下输出:

...will emit the following output:

foo && echo bar

...而不是下面,否则会预期:

...instead of the following, which would otherwise be expected:

foo
bar

特种作业人员和扩张都没有兑现。

没有 $(富),没有 $ foo的,没有≤(富)

这篇关于什么是EVAL / bash的-c点,而不是仅仅评估一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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