statement blocks Mechanism in Shell scripting?
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
fi
(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
and
( 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'
}
are.
Related videos on Youtube
alamin
Updated on September 18, 2022Comments
-
alamin over 1 year
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 echo add_record_tracks }
Please explain how the code is executing in the statement block...
-
Hauke Laging over 6 yearsThe code within the braces is executed the same way as if there were no braces.
-
-
Dan M. over 4 years@Kusalananda, sorry if it's offtopic but is this
{}
syntax - bash specific, or is it POSIX-compliant? -
Dan M. over 4 years@Kusalananda thanks. I'll look into other causes that may explain why my script has an empty output under dash but not zsh and bash.
-
Kusalananda over 4 years@DanM. You could ask a question about it.