Search code examples
bashverbosity

Cannot redirect to a file descriptor stored in a variable


Editor's note: This question has undergone several revisions that altered the nature of the problem, potentially invalidating older comments and answers; its original title was "Cannot redirect Bash output to /dev/null".

I'm trying to create a small Bash script for which I'd like to implement a silent mode. Basically I'd just like to hide most of the output by default and, in case I run it with -v, show all output.

So at the beginning of my script I've put :

#!/bin/bash
declare output=''
if [ "$1" = -v ]; then
  output="&1"
else
  output="/dev/null"
fi

Then in my scripts I have:

{
  # whatever commands...
} > $output 2>&1

The silent mode works well. However, if I try the verbose mode, a file called either & or &1 (based on my output variable) is being created. Also, the file is empty. This is not the desired outcome: I want the output to stay on the terminal!

Is this due to the order in which I redirect or is it my variable which is wrong? EDIT: The script now works fully, by replacing "&1" as output value with "/dev/tty".


Solution

  • Most probably the error output is getting printed. Note that with > /dev/null only stdout is redirected and stderr is not. You can use 2>&1 to redirect stderr to stdout before redirecting stdout. Something like:

    {
      # whatever commands...
    } > $output 2>&1