Wakan Tanka
Wakan Tanka

Reputation: 8042

curly brackets inside command substitution which is assigned to variable in bash

What is the purpose of curly brackets inside command substitution which is assigned to variable in bash e.g.

VAR=$({})

There is code where I saw this construction:

#!/bin/bash
test $# -ge 1 || { echo "usage: $0 write-size [wait-time]"; exit 1; }
test $# -ge 2 || set -- "$@" 1
bytes_written=$(
{
    exec 3>&1
    {
        perl -e '
            $size = $ARGV[0];
            $block = q(a) x $size;
            $num_written = 0;
            sub report { print STDERR $num_written * $size, qq(\n); }
            report; while (defined syswrite STDOUT, $block) {
                $num_written++; report;
            }
        ' "$1" 2>&3
    } | (sleep "$2"; exec 0<&-);
} | tail -1
)
printf "write size: %10d; bytes successfully before error: %d\n" \
    "$1" "$bytes_written"

Taken from here

Upvotes: 1

Views: 1287

Answers (1)

Barmar
Barmar

Reputation: 780843

Curly braces are used to group multiple commands in a script. They have the same meaning inside a command substitution as they do at top-level.

They're like wrapping the commands in parentheses, except that curly braces don't create a subshell, while parentheses do (this matters if the commands do things like variable assignments or cd). Also, unlike parentheses, curly braces are not self-delimiting, so you need to have whitepace after the { and a command delimiter (e.g. ; or newline) before the }.

This is documented in the Bash manual section on Grouping Commands

Upvotes: 2

Related Questions