Discussion:
[Help-bash] Is there any practical difference between { } & and ( ) &?
Peng Yu
2018-11-28 16:01:27 UTC
Permalink
Hi,

Both { } & and ( ) & start a new bash process. In this sense, do they
have any differences (other than some trivial syntax requirements like
{ } & should include the ";")? Thanks.

$ cat ./main.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -v
{ echo "{$BASHPID"; } &
( echo "($BASHPID" ) &
echo "$BASHPID"
wait
$ ./main.sh
{ echo "{$BASHPID"; } &
( echo "($BASHPID" ) &
echo "$BASHPID"
23876
wait
(23878
{23877
--
Regards,
Peng
Jesse Hathaway
2018-11-28 18:12:02 UTC
Permalink
Post by Peng Yu
Hi,
Both { } & and ( ) & start a new bash process. In this sense, do they
have any differences (other than some trivial syntax requirements like
{ } & should include the ";")? Thanks.
$ cat ./main.sh
#!/usr/bin/env bash
set -v
{ echo "{$BASHPID"; } &
( echo "($BASHPID" ) &
echo "$BASHPID"
wait
$ ./main.sh
{ echo "{$BASHPID"; } &
( echo "($BASHPID" ) &
echo "$BASHPID"
23876
wait
(23878
{23877
If you background a command it is executed in a subshell, but
if you execute a command in the foreground within brackets a
subshell is not created, whereas with parens a subshell is created.

#!/bin/bash
echo "MAIN PID $$"
echo 'brackets'
{ echo $BASHPID; }
echo 'parens'
( echo $BASHPID )
echo 'background brackets'
{ echo $BASHPID; } &
wait
echo 'background parens'
( echo $BASHPID ) &
wait

Output:
MAIN PID 23607
brackets
23607
parens
23608
background brackets
23609
background parens
23610

Loading...