Linux, FreeBSD, Juniper, Cisco / Network security articles and troubleshooting guides

It is currently Sat Nov 18, 2017 4:33 pm

Message body:
Enter your message here, it may contain no more than 60000 characters. 

:D :) ;) :( :o :shock: :? 8-) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :!: :?: :idea: :arrow: :| :mrgreen: :geek: :ugeek:
Font size:
Font colour
BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON
Disable BBCode
Disable smilies
Do not automatically parse URLs
Confirmation code
Confirmation code:
In an effort to prevent automatic submissions, we require that you enter both of the words displayed into the text field underneath.

Topic review - bash: Redirecting standard error to a shell variable and standard output to a file
Author Message
Post subject: bash: Redirecting standard error to a shell variable and standard output to a file  |  Post Posted: Mon Oct 31, 2011 6:54 am
A little background from bashref:
Quote: Grouping Commands

Bash provides two ways to group a list of commands to be executed as a unit. When commands are grouped, redirections may be applied to the entire command list. For example, the output of all the commands in the list may be redirected to a single stream.

( list )

Placing a list of commands between parentheses causes a subshell environment to be created (see Command Execution Environment), and each of the commands in list to be executed in that subshell. Since the list is executed in a subshell, variable assignments do not remain in effect after the subshell completes.

{ list; }

Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.

In addition to the creation of a subshell, there is a subtle difference between these two constructs due to historical reasons. The braces are reserved words, so they must be separated from the list by blanks or other shell metacharacters. The parentheses are operators, and are recognized as separate tokens by the shell even if they are not separated from the list by whitespace.

The exit status of both of these constructs is the exit status of list.

In my example, the of commands is only "ls".
# ls file.txt nonexist.txt
ls: nonexist.txt: No such file or directory

file.txt exists and nonexist.txt doesn't.

Following ERROR variable will take the value of the standard error from ls command and the standard output will be sent to output file:
ERROR=$( { ls file.txt nonexist.txt >output ; } 2>&1)
# echo $ERROR
ls: nonexist.txt: No such file or directory
# cat output

As stated in bashref, bash shell treats the braces as reserved words and they need to be separated from the command by a space in this case.
Jump to:  
News News Site map Site map SitemapIndex SitemapIndex RSS Feed RSS Feed Channel list Channel list

Delete all board cookies | The team | All times are UTC - 5 hours [ DST ]