Nasser Heidari

2012-01-06

Bash: Saving or Grouping Output from Several Commands

Filed under: Linux — Nasser Heidari @ 23:53
Tags:

You want to capture the output with a redirect, but you’re typing several commands
on one line.
$ pwd; ls; cd ../elsewhere; pwd; ls > /tmp/all.out
The final redirect applies only to the last command, the last ls on that line. All the
other output appears on the screen (i.e., does not get redirected).

Solution:

Use braces { } to group these commands together, then redirection applies to the
output from all commands in the group. For example:

$ { pwd; ls; cd ../elsewhere; pwd; ls; } > /tmp/all.out

There are two very subtle catches here. The braces are actually
reserved words, so they must be surrounded by white space. Also, the
trailing semicolon is required before the closing space.
Alternately, you could use parentheses ( ) to tell bash to run the commands in a subshell,
then redirect the output of the entire subshell’s execution. For example:

$ (pwd; ls; cd ../elsewhere; pwd; ls) > /tmp/all.out

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.