Search code examples
shellash

How can I have variable redirection in a shell script?


If I have a script with the command

echo xx 2>&1 >junk

I get a file with "xx" in it. If I have a script with

R="2>&1 >junk"
echo xx $R

the script prints "xx 2>&1 >junk", instead of creating the file I desire.
How can I have a redirection that is variable? In the case at hand, I either want to do the redirection, or just set the variable to the empty string to do no redirection. But I need to do it for a number of commands, so I would like to do it as a variable.
Note: environment is embedded Linux with an ash shell from busybox.


Solution

  • Use eval:

    R="2>&1 >junk"
    eval echo xx $R
    

    BTW, if you want the stderr of the command redirected to the file, you must reorder the redirections. cmd 2>&1 > file will print stderr to the original stdout, but cmd > file 2>&1 will direct both stderr and stdout to the named file.