JHAWN
JHAWN

Reputation: 399

Bash: ( commands ) | command

I stumbled upon Zenity, a command-line based GUI today. I noticed the there was some syntax of the form ( commands ) | command. Could anyone shed some light on what this is and where I can read more about it?

I found the below script within the docs

(
  echo "10" ; sleep 1
  echo "# Updating mail logs" ; sleep 1
  echo "50" ; sleep 1
  echo "This line will just be ignored" ; sleep 1
  echo "100" ; sleep 1
) |
 zenity --progress \
   --title="Update System Logs" \
   --text="Scanning mail logs..." \
   --percentage=0

Upvotes: 1

Views: 75

Answers (2)

tripleee
tripleee

Reputation: 189377

The parentheses create a subshell, with all the implications that it has for the current shell.

  • The subshell cannot change the environment of the parent shell; sometimes, you want a subshell so that you can, say, quickly cd to a different directory without affecting the working directory for the rest of the script
  • The subshell has a single standard input and a single standard output stream; this is frequently a reason to start a subshell
  • The parent shell waits while the subshell completes the commands (unless you run it in the background)

If it helps,, think of ( foo; bar ) as a quick way to say sh -c 'foo; bar'.

A related piece of syntax is the brace, which runs a compound command in the current shell, not a subshell.

test -f file.rc || { echo "$0: file.rc not found -- aborting" >&2; exit 127; }

The exit in particular causes the current shell to exit with a failure exit code, while a subshell which exits does not directly affect the rest of the parent shell script.

(Weirdly, POSIX requires a statement terminator before the closing brace, but not before the closing parenthesis.)

Upvotes: 1

Mike Holt
Mike Holt

Reputation: 4612

The parentheses are delimiting a subshell, which means the commands inside the parens are run in a separate process, and interpreted by a separate instance of the bash interpreter. In this case, it appears they are using a subshell just to group together all the echo and sleep commands so that they can then pipe the combined output of the entire group of commands through zenity. Which makes sense given that the goal in this example is to simulate a progress bar.

You can read more about subshells here: http://tldp.org/LDP/abs/html/subshells.html

Upvotes: 1

Related Questions