bash 文件中的 exec 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3589033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
exec line from file in bash
提问by Quamis
I'm trying to read commands from a text file and execute each line from a bash script.
我正在尝试从文本文件中读取命令并从 bash 脚本中执行每一行。
#!/bin/bash
while read line; do
$line
done < "commands.txt"
In some cases, if $linecontains commands that are meant to run in background, eg command 2>&1 &they will not start in background, and will run in the current script context.
在某些情况下,如果$line包含旨在在后台运行的命令,例如command 2>&1 &它们不会在后台启动,而是会在当前脚本上下文中运行。
Any ideea why?
知道为什么吗?
回答by ghostdog74
if all your commands are inside "commands.txt", essentially, you can call it a shell script. That's why you can either source it, or run it like normal, ie chmod u+x , then you can execute it using sh commands.txt
如果您的所有命令都在“commands.txt”中,则本质上,您可以将其称为 shell 脚本。这就是为什么你可以获取它,或者像正常一样运行它,即 chmod u+x ,然后你可以使用它来执行它sh commands.txt
回答by Gordon Davisson
I don't have anything to add to ghostdog74's answer about the right way to do this, but I can cover why it's failing: The shell parses I/O redirections, backgrounding, and a bunch of other things before it does variable expansion, so by the time $lineis replaced by command 2>&1 &it's too late to recognize 2>&1and &as anything other than parameters to command.
我没有什么可以添加到 ghostdog74 的关于正确方法的答案中,但我可以说明它失败的原因:shell 在进行变量扩展之前解析 I/O 重定向、背景和一堆其他东西,所以到时候$line被command 2>&1 &识别为时已晚,2>&1并且&除了参数之外的任何东西都为command.
You could improve this by using eval "$line"but even there you'll run into problems with multiline commands (e.g. while loops, if blocks, etc). The sourceand shapproaches don't have this problem.
您可以通过使用来改进这一点,eval "$line"但即使在那里您也会遇到多行命令的问题(例如,while 循环、if 块等)。该source和sh方法不存在这个问题。

