Linux redirects the Print message and saves the file --- bash redirections using Exec

Source: Internet
Author: User
Jun 11,201 0 by Mitch frazy in

  • How-tos

If you 've used the command line much at all you know about I/O redirectionfor redirecting input to and/or output from a program. what you don't see all that often or that you may not be familiarwith is redirecting I/O inside a bash script. and I'm not talking
About redirections that you use whenyour script executes another command, I'm talking about redirectingyour script's I/O once it has already started executing.

As an example, let's say that you want to add-- LogOptionto your script and if the user specifies it You want all the outputto go to a log file rather than to the stdout. Of course, the user cocould
Simply redirect the output on the command line, but let's assume there's a reason why that option doesn't appeal to you. so, to provide this feature in your script you can do:

#!/bin/bashecho hello# Parse command line options.# Execute the following if --log is seen.if test -t 1; then    # Stdout is a terminal.    exec >logelse    # Stdout is not a terminal, no logging.    falsefiecho goodbyeecho error >&2

The IF statement usesTestTo see if file descriptor Number One isconnected to a terminal (1 being the stdout). If it is then the exec command re-opens it for writing on thefile named
Log. The exec command without a command but withredirections executes in the context of the current shell, it's the means by which you can open and close files and duplicate file descriptors. If file
Descriptor number one is not on a terminal then we don't change anything.

If you run this command you'll see the first ECHO and the lastecho are output to the terminal. the first one happens before the redirection and the secondone is specifically redirected to stderr (2 being stderr ). so, how do you get stderr into the log file
Also? Just one simple change is required to the exec statement:

#!/bin/bashecho helloif test -t 1; then    # Stdout is a terminal.    exec >log 2>&1else    # Stdout is not a terminal, no logging.    falsefiecho goodbyeecho error >&2

Here the exec statement re-opens stdout on the log file and thenre-opens stderr on the same thing that stdout is opened on (this is how you duplicate file descriptors, aka DUP them ). note that order is important here: if you change the orderand re-open stderr
First (I. e.Exec
2> & 1> log), Then it will still be on the terminal since you 'reopening it on the same thing stdout is on and at this point it 'sstill the terminal.

Perhaps mainly as an exercise, let's try to do the same thingeven if the output is not to the terminal. we can't do what we did above since re-opening stdout on thelog file, when it's currently connected to a file redirectionor to a pipeline, wowould break
The redirection/pipeline that the userspecified when the command was invoked.

Given the following command as an example:

bash test.sh | grep good

What we want to do is manipulate things so that it appears thatthe following command was executed instead:

bash test.sh | tee log | grep good

Your first thought might be that you cocould change the exec statementto something like this:

exec | tee log &       # Won't work

And tell exec to re-open stdout on a background pipeline
Tee, But that won't work (although Bash doesn't complain about it ). this just pipes exec's output to tee, and since exec doesn't produce any output in this instance, Tee simply creates an empty file and exits.

You might also think that you can try some dup-ing of file descriptors andstart tee in the background with it taking input from and writing output todifferent file descriptors. and you can do that, but the problem is that there's no way to create anew Process
That has its standard input connected to a pipe so that wecan insert it into the pipeline (although see the postscript at the end of this Article ). if we cocould do this, the standard output of the tee command wocould be easy sinceby default that goes to the same
Place the main script's output goes to, so wecocould just close the main script's output and connected it to our pipe (if we just had a way to create it ).

So are we at a dead end? Ahhhh no, that wocould be a different operating systemyou're thinking of. The solution is actually described in the last sentence of theprevious paragraph. We just need a way to create a pipe, right? Well let's use named pipes.

#!/bin/bashecho helloif test -t 1; then    # Stdout is a terminal.    exec >logelse    # Stdout is not a terminal.    npipe=/tmp/$$.tmp    trap "rm -f $npipe" EXIT    mknod $npipe p    tee <$npipe log &    exec 1>&-    exec 1>$npipefiecho goodbye

Here, if the script's stdout is not connected to the terminal, we create a named pipe (a pipe that exists in the file-System) using mknodand setup a trap to delete it on exit. then we start tee in the background reading from the named pipe and writing to
Log File. remember that tee is also writing anything that it reads on its stdinto its stdout. also remember that tee's stdout is also the same as the script's stdout (our main script, the one that invokes tee) So the output from Tee's stdoutis going to go wherever
Our stdout is currently going (I. e. to the user's redirection or pipeline that was specified on the command line ). so at this point we have tee's output going where it needs to go: into the redirection/pipeline specified by the user.

Now all we need is to get tee reading the right data. and since tee is reading from a named pipe all we need to dois redirect our stdout to the named pipe. we close our current stdout (
Exec 1> &-) Andre-open it on the named pipe (
Ezec 1> $ npipe). Note that since tee is also writing to the redirection/pipeline that wasspecified on the command line, our closing the connection does notbreak anything.

Now if you run the command and pipe it's output to grep as aboveyou'll see the output in the termimal and it will also be saved in the log file.

Please such journeys are possible, let the man page be your guide!

P.s. There's another way to do this using bash 4's coproc statement, butthat'll wait for another time.

This article from: http://www.linuxjournal.com/content/bash-redirections-using-exec

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.