Skip to main content

Specifying redirection options through a variable, in an exec command [Resolved]

I want to be able to specify the redirection command/options via a variable (that I might set based on certain conditions, etc.). But when I run this bash script for example :

REDIRECT=">>test"
exec echo hi ${REDIRECT}

I get (via bash -x output) :

+ REDIRECT='>>test'
+ exec echo hi '>>test'
hi >>test

It looks like exec is placing the value of REDIRECT variable inside single quotes, instead of literally substituting its value.

How can I fix/get around this?


Question Credit: user98708
Question Reference
Asked September 21, 2019
Posted Under: Unix Linux
22 views
3 Answers

I think that the only way to do this would be to use eval and all classic caveats about eval would apply. That said, you could do something like this:

REDIRECT=">>test"
eval echo hi ${REDIRECT}

credit: Community
Answered September 21, 2019

You can redirect the whole of stdout to a file with the exec command eg

exec >> outfile

Now any output will be sent to outfile.

For example:

#!/bin/bash

exec >> outfile

echo start
echo hello
echo there
echo end

If we run this:

$ ./x

$ cat outfile 
start
hello
there
end

$ ./x

$ cat outfile
start
hello
there
end
start
hello
there
end

So we can see each execution appends.

This becomes simple to add in a test

if [ -n "$REDIRECT" ]
then
  exec >> $REDIRECT
fi

credit: Stephen Harris
Answered September 21, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA