More Bash Redirections

October 6th, 2009 by Mitch Frazier in

Your rating: None Average: 4.7 (7 votes)

Everybody's seen redirection in bash commands, that's pretty common, but bash also allows you to define redirections when you define functions. This causes the redirections to be evaluated/executed whenever the function is called. This feature doesn't really give you any new features, just another way to express existing features.

The syntax for this is simple, you simply append the redirections onto the end of the function defintion:

function testy()
{
        ...
} < testy.in > testy.out 2> testy.err

Now whenever the function testy is called its input will come from testy.in, its output will go to testy.out and any errors will go to testy.err.

Since the redirections are evaluated when the function is called the redirection(s) can use variables and the variables are also evaluated when the function is called. So you could do something like this:

#!/bin/bash

function testy()
{
    echo testy westy
} >$out

out=jj1
testy
out=jj2
testy

This causes the output of the function to go to a different file with each call. The first call's output goes to jj1 and the second's to jj2:

$ bash j.sh; more jj?
::::::::::::::
jj1
::::::::::::::
testy westy
::::::::::::::
jj2
::::::::::::::
testy westy

As I mentioned earlier, there's not any real new capability here, you could also accomplish the same thing this way:

#!/bin/bash

function testy()
{
    echo testy westy
}

testy >jj1
testy >jj2

One possible use of this feature might be to put all your code inside a main function and then redirect it's error output so that you make sure it always gets captured:

#!/bin/bash

log=kk
function error()
{
    echo "$*" >&2
}
function testy()
{
    error testy westy
}

function testy2()
{
    error testy2 westy2
}

function main()
{
    testy
    testy2
} 2>$log

main

Running this produces:

$ bash k.sh ;cat kk
testy westy
testy2 westy2

Since bash also allows redirection to be included on {...} blocks/lists you could accomplish the same thing with the following:

#!/bin/bash

log=mm
function error()
{
    echo "$*" >&2
}
function testy()
{
    error testy westy
}

function testy2()
{
    error testy2 westy2
}

{
testy
testy2
} 2>$log

You can also use redirections on (...) blocks/lists but that causes the commands to be executed in a sub-shell, which isn't necessary here and which may cause problems since the sub-shell is a different process.

If you're wondering if you can override the redirections in the actual call, the answer is no. If you try to override them all that happens is that redirections in the call are executed/evaluated first then the ones in the function definition replace them. For example, in the following:

#!/bin/bash

function testy()
{
    echo testy westy
} >nn1

testy >nn2

The output file specified in the call (nn2) gets created but nothing gets written to it.

Also note that pipe "redirections" do not work, but here documents do:

#!/bin/bash

function testy()
{
    while read line
    do
        echo $line
    done
} <<EOF
hello
there
EOF

testy

Running this produces:

$ bash o.sh
hello
there
__________________________

Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.


Special Magazine Offer -- Free Gift with Subscription
Receive a free digital copy of Linux Journal's System Administration Special Edition as well as instant online access to current and past issues. CLICK HERE for offer

Linux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
ILGUIZ LATYPOV's picture

an adjustment

On October 15th, 2009 ILGUIZ LATYPOV (not verified) says:

Just in case the script is interrupted with a Ctrl-C or a pipe overflow, two more signals could be treated by the trap block,


trap "
...
" EXIT SIGINT SIGPIPE

Jenny's picture

Please Help!

On October 9th, 2009 Jenny (not verified) says:

Um hi.

I've actually been wanting to use Linux Ubuntu, but I've been having trouble and don't really have anyone to help me.

This guy at school told me to use Linux Ubuntu and he said it's a really good program and gave me a CD that says "Ubuntu Warty". He said its the same as using a Mac. I put it in and double click on it and can't get it to work right.

I also try to go to Start/Add new programs/ and still can't figure it out.

I get really tired of XP and everything and really want to try something new.

Sorry I don't know much about computers.

ILGUIZ LATYPOV's picture

more redirects

On October 9th, 2009 ILGUIZ LATYPOV (not verified) says:


#! /bin/bash
# This will redirect both stdout and stderr of all subsequent commands in the script.
exec 1> "${log_file}" 2>&1
set -x
OTHER_COMMANDS...


#! /bin/bash
# This will duplicate the the stdout/stderr capture to the screen almost synchronously.
log_file="log.txt"
tail -F "${log_file}" &
TAIL_PID=$!
trap "
        err=\$?
        set +x
        echo Exit code \$err
        sleep 2
        exec 2>&12 1>&11
        kill -HUP $TAIL_PID
        echo Exit code \$err >&2
        exit \$err
    " EXIT
exec 11>&1 12>&2 1> "${log_file}" 2>&1
set -x
OTHER_COMMANDS...

Post new comment

Please note that comments may not appear immediately, so there is no need to repost your comment.
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd> <i> <b>
  • Lines and paragraphs break automatically.

More information about formatting options

Newsletter

Each week Linux Journal editors will tell you what's hot in the world of Linux. You will receive late breaking news, technical tips and tricks, and links to in-depth stories featured on www.linuxjournal.com.
Sign up for our Email Newsletter

Tech Tip Videos

From the Magazine

December 2009, #188

If last month's Infrastrucuture issue was too "big" for you then try on this month's Embedded issue. Find out how to use Player for programming mobile robots, build a humidity controller for your root cellar, find out how to reduce the boot time of your embedded system, and if you're new to embedded systems find out the basics that go into one. You can also read about the Beagle Board, the Mesh Potato and a spate of other interestingly named items. And along with our regular columns don't miss our new monthly column: Economy Size Geek.


Read this issue