majic bunnie
majic bunnie

Reputation: 1405

Output redirection using a bash variable

I would like to do something along these lines, but most combinations I have tried have failed:

export no_error="2 > /dev/null"
./some_command $no_error

To run that command and redirect the output using a variable instead of typing the command. How would I go about doing this?

Upvotes: 3

Views: 89

Answers (1)

Carl Norum
Carl Norum

Reputation: 224904

The shell doesn't re-evaluate your no_error variable when you use it like that. It just gets passed to ./some_command as a command-line argument. You can get the behaviour you want by using eval. From the bash manual:

eval [arguments]

The arguments are concatenated together into a single command, which is then read and executed, and its exit status returned as the exit status of eval. If there are no arguments or only empty arguments, the return status is zero.

Here's an example for your case:

export no_error="2>/dev/null"
eval ./some_command $no_error

Note that you can't have a space between the 2 and the >. I'm guessing that's just a typo in your question, though.

Upvotes: 2

Related Questions