In Beginning Linux Programming book. There is a secition about Statement Block. In that Portion the explanation looks like the following.

Statement Blocks

If you want to use multiple statements in a place where only one is allowed, such as in an AND or OR list, you can do so by enclosing them in braces {} to make a statement block. For example, see the following code:

get_confirm && {
    grep −v "$cdcatnum" $tracks_file > $temp_file 
    cat $temp_file > $tracks_file

Please explain how the code is executing in the statement block...

  • The code within the braces is executed the same way as if there were no braces. – Hauke Laging Sep 4 '17 at 19:44

The code within { ... } execute exactly the way it would have executed without the curly braces, except now it's dependent on the exit status of get_confirm.

If get_confirm exits with a zero exit status ("success"), the block executes, otherwise not.

It's equivalent to

if get_confirm; then
    # the contents of the block goes here

(which I think looks nicer)

The book's example is IMHO not a good example of a common use of { ... }. A better example would have been

{ echo 'hello world'; date; } >file

which uses a single redirection to redirect the standard output of both commands in the { ... } block to the same file.

This is similar to (and has the same effect, in this instance, as)

( echo 'hello world'; date ) >file

but the statements within { ... } executes in the same environment as the shell, whereas the statements in ( ... ) executes in a subshell (a separate environment).

You can see the difference with

{ a=42; }; echo $a


( a=1973 ); echo $a

The first will output 42 whereas the second will not output 1973 (the assignment happens in a subshell and it can't affect the environment outside).

Notice about grammar: The closing } of a { ... } block must follow a newline or a ;. { echo 'hello' } is not valid, while both { echo 'hello'; } and

    echo 'hello'


  • always @Kusalananda on rescue.. – alamin Sep 4 '17 at 21:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.