Dorleeze Dorleeze - 7 months ago 23
Bash Question

How to pass variable to do external action but not command parameter in bash

I want to do a output redirection in bash for passing variable in shell.

For example:

OPTION=">> /tmp/log1 2>&1"
ADD_OPTION=($OPTION)
ls ${ADD_OPTION[@]}


I want to record result of
ls
command in /tmp/log1.
So as to,
ls >> /tmp/log1 2>&1
to be executed.

But unfortunately,
${ADD_OPTION[@]}
was treated as parameter of
ls
.
The actual result is:

ls: >>: No such file or directory
ls: /tmp/log1: No such file or directory
ls: 2>&1: No such file or directory


What should I do for it?

Answer

You can use eval:

eval ls ${OPTION}

As an obvious note, be careful with eval.

Example:

$ OPTION=">> /tmp/log1 2>&1"

$ eval ls ${OPTION}

$ cat /tmp/log1 
1
2
3