bash 中的代码块用法 { }

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5717972/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:49:19  来源:igfitidea点击:

Code block usage { } in bash

bashshell

提问by Ankur Agarwal

I was wondering why code block was used in this example below:

我想知道为什么在下面的这个例子中使用了代码块:

possibly_hanging_job & { sleep ${TIMEOUT}; eval 'kill -9 $!' &> /dev/null; }

This could have been written like this ( without using code block as well) ..right ?

这本可以这样写(也不使用代码块)..对吗?

possibly_hanging_job & 
sleep ${TIMEOUT}
eval 'kill -9 $!' &> /dev/null

回答by Brandon Rhodes

Putting the last two commands in braces makes it clear that “These are not just two additional commands that we happento be running after the long-running process that might hang; they are, instead, integral to getting it shut down correctly before we proceed with the rest of the shell script.” If the author had instead written:

将最后两个命令放在大括号中可以清楚地表明“这不仅仅是我们在可能挂起的长时间运行的进程之后碰巧运行的另外两个命令;相反,它们是在我们继续执行 shell 脚本的其余部分之前正确关闭它的组成部分。” 如果作者改为写:

command &
a
b
c

it would not be completely clear that aand bare just part of getting commandto end correctly. By writing it like this:

它不会是完全清楚,a并且b都得到的只是部分command正确地结束。通过这样写:

command & { a; b; }
c

the author makes it clearer that aand bexist for the sake of getting commandcompletely ended and cleaned up before the actualnext step, c, occurs.

笔者使得它更清晰的是ab存在的越来越着想command完全结束,之前清理实际的下一步c,会出现。

回答by bmk

Actually I even wonder why there's an eval. As far as I see it should also work without that.

其实我什至想知道为什么有一个eval. 据我所知,它也应该在没有它的情况下工作。

Regarding your actual question: I guess the code block is there to emphasize that the sleepbelongs to kill. But it's not necessary. It should also work like this:

关于您的实际问题:我想代码块是为了强调sleep属于kill. 但这不是必需的。它也应该像这样工作:

possibly_hanging_job & sleep ${TIMEOUT}; kill -9 $! &> /dev/null