Blagus
Blagus

Reputation: 65

Bash script - stdout file descriptor?

I have the following in my script:

OUTFILE=./output.log
echo "foo" >> ${OUTFILE}

It works just fine when OUTFILE is an actual file path. However, sometimes I'd like to see the output on stdout by modifying OUTFILE but it doesn't work. I tried with 1 and &1, both quoted and unquoted, as well as leaving it empty.
It just keeps telling me this:

./foo.sh: line 2: ${OUTFILE}: ambiguous redirect

Upvotes: 2

Views: 3686

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80931

Use /dev/stdout as your filename for this. (See the Portability of “> /dev/stdout”.)

You can't use &1 in the variable because of parsing order issues. The redirection tokens are searched for before variable expansion is performed. So when you use:

$ o='&1'
$ echo >$o

the shell scans for redirection operators and sees the > redirection operator and not the >& operator. (And there isn't a >>& operator to begin with anyway so your appending example wouldn't work regardless. Though newer versions of bash do have an &>> operator for >> file 2>&1 use.)

Upvotes: 7

123
123

Reputation: 11216

Im guessing you want to do one of these

Print to file

OUTFILE=./output.log
echo "foo" >> "${OUTFILE}"

Print to stdout

OUTFILE=/dev/stdout
echo "foo" >> "${OUTFILE}"

or just

echo "foo"

Print to file and stdout

OUTFILE=./output.log
echo "foo" | tee  "${OUTFILE}"

Upvotes: 6

Related Questions