user180574
user180574

Reputation: 6094

What is the purpose of double parentheses with file redirection?

I see this with the partclone command, for example

( ( partclone.restore -s ${SOUR_PART} -o ${DEST_PART} 2>&3 ) 3>&1 ) | ... 

What is the meaning or purpose of 2>&3 ) 3>&1 )? Is it the same as

partclone.restore -s ${SOUR_PART} -o ${DEST_PART} 2>&1

...? If not, what is the difference?

Upvotes: 0

Views: 977

Answers (3)

lurker
lurker

Reputation: 58324

The expression

2>&3

Tells shell to redirect any output destined for file descriptor 2 (which is standard error) to file descriptor 3

3>&1

Says to redirect any I/O destined for file descriptor 3 to file descriptor 1 (standard output).

The parentheses help the shell parse it all out and create a subshell. The inside parentheses have:

( partclone.restore -s ${SOUR_PART} -o ${DEST_PART} 2>&3 )

Which indicates a particular redirection of I/O within that subshell. Then this is wrapped in another set of parentheses for another subshell with its own redirection:

( the_command_shown_above 3>&1 ) | ...

And all the standard output is then piped into whatever command is represented by ...


One interesting use of this method is if you want to capture stderr rather than stdin with a command that normally only accepts stdin. Consider:

( (my_cmd 2>&1 1>&3) | error_processor ) 3>&1

This executes my_cmd and send its standard output to the terminal (ultimately) but routes the error output of my_cmd to the command error_processor which expects its input from stdin.

Upvotes: 2

SeeJayBee
SeeJayBee

Reputation: 1259

The double open paren creates two sub shells.

The 2>&3 in the inner most shell sends stderr to file descriptor 3

The 3>&1 in the outer most shell sends file descriptor 3 to stdout, which is then piped to the next command.

See IO redirection in The Linux Documentation Project here: http://www.tldp.org/LDP/abs/html/io-redirection.html

and for a redirect script that will blow your mind, see the exercise here: http://www.tldp.org/LDP/abs/html/ioredirintro.html

Upvotes: 2

phs
phs

Reputation: 11061

It creates a subshell, which allows another step of redirection.

Upvotes: 0

Related Questions