[英]What's the difference between 'eval $command' and $command?
有什么區別:
eval echo lala
和:
command="echo lala"
$command
他們似乎都有相同的效果,但我可能會遺漏一些東西。 另外,如果它們確實具有相同的效果,那么eval
命令的重點是什么?
嘗試這個:
y='FOO=hello; echo $FOO'
eval $y
打印hello
。 但是這個:
$y
說:
-bash:FOO = hello;:找不到命令
因此,當你說eval $y
,就好像你已經將$y
的內容輸入到解釋器中一樣。 但是當你只說$y
它需要是一個可以運行的命令,而不是解釋器需要解析的其他一些令牌(在上面的例子中,是一個變量賦值)。
如果您知道變量包含可執行命令,則可以在不使用eval
情況下運行它。 但是如果變量可能包含Bash代碼,這不僅僅是一個可執行命令(即你可以想象傳遞給C函數exec()
),你需要eval
。
要擴展@ JohnZwinck的最佳答案 ,請查看以下示例:
command='ls | wc -l'
eval $command
# outputs the correct result => 17
$command
ls: -l: No such file or directory
ls: wc: No such file or directory
ls: |: No such file or directory
command='ls -l $PWD'
eval $command
# outputs the contents of current directory
$command
# runs 'ls -l $PWD' literally as a command and ls tries to lookup $PWD as a file
ls: $PWD: No such file or directory
因此, eval
builtin以與shell相同的方式解釋其參數。 但是,在$command
情況下,shell會擴展變量,並將內容視為命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.