Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code block usage { } in bash

Tags:

bash

shell

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
like image 215
Ankur Agarwal Avatar asked Apr 19 '11 14:04

Ankur Agarwal


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What is code block :: bash?

code:: bash seems to mostly be used in the Cilium docs for interactive shell sessions, although really those should be using something like .. code:: shell-session because they include commands and example output. This is a bit different from straight bash scripts, and the highlighter would treat this better.

What is $1 and $2 in bash?

$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1)

What does %% do in bash?

In your case ## and %% are operators that extract part of the string. ## deletes longest match of defined substring starting at the start of given string. %% does the same, except it starts from back of the string.


2 Answers

Putting the last two commands in braces makes it clear that “These are not just two additional commands that we happen to 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:

command &
a
b
c

it would not be completely clear that a and b are just part of getting command to end correctly. By writing it like this:

command & { a; b; }
c

the author makes it clearer that a and b exist for the sake of getting command completely ended and cleaned up before the actual next step, c, occurs.

like image 63
Brandon Rhodes Avatar answered Sep 19 '22 19:09

Brandon Rhodes


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

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

possibly_hanging_job & sleep ${TIMEOUT}; kill -9 $! &> /dev/null
like image 33
bmk Avatar answered Sep 17 '22 19:09

bmk