puk
puk

Reputation: 16782

How to store a reference to STDOUT/STDERR inside a variable

I can call a shell script like so:

foo --out-file=build/logs/foo.out --err-file=build/logs/foo.err

and in the

script I have something like so

#!/bin/bash
OUTFILE=null
ERRFILE=null

while [[ $# -gt 0 ]]
do
  key="$1"

  case $key in
    -o|--out-file)
    OUTFILE=$2
    shift
    shift
    ;;
    case $key in
    -e|--err-file)
    ERRFILE=$2
    shift
    shift
    ;;
    *)
    shift
    ;;
  esac
done
if [ "$OUTFILE" != null ] && [ "$ERRFILE" != null ]
then
  ls > $OUTFILE 2>$ERRFILE
elif [ "$OUTFILE" != null ]
then
  ls > $OUTFILE
elif [ "$ERRFILE" != null ]
then
  ls 2>$ERRFILE
else
  ls
fi

Is there any way to set OUTFILE and ERRFILE to hold the values to STDOUT/STDERR so I can just initialize them to that (ie. OUTFILE=$STDERR) to avoid so man if/elif/else statements?

Upvotes: 0

Views: 199

Answers (1)

Barmar
Barmar

Reputation: 780974

What you can do is perform the redirect with the exec command, which redirects for the rest of the script.

while [[ $# -gt 0 ]]
do
  key="$1"

  case $key in
    -o|--out-file)
        exec >"$2"
        shift 2
        ;;
    -e|--err-file)
        exec 2>"$2"
        shift 2
        ;;
    *)
        shift
        ;;
  esac
done

Then the ls command will write to the files without needing its own redirection.

Upvotes: 2

Related Questions