Ubuntu – Toggle Bash redirection with a variable

bashredirect

MUTE='&> /dev/null'
echo "text" $MUTE

Is there a way to make that work keeping the redirection inside the variable?

Best Answer

IMHO it would be more elegant to use the presence / value of the variable to conditionally close the file descriptors e.g.

$ cat myscript.sh
#!/bin/bash

if [ -n "$MUTE" ]; then
    exec &>-
fi

echo somestuff
echo someerr >&2

then

$ ./myscript.sh
somestuff
someerr

but

$ MUTE=yes ./myscript.sh
$

If you really want to toggle the redirection, you could consider creating a shell function that duplicates the file descriptor(s) before closing them, and then restores the duplicates to re-enable the original streams e.g.

#!/bin/bash

function mute {
  case "$1" in
    "on") 
      exec 3>&1-
      exec 4>&2-
    ;;
    "off") 
      exec 1>&3-
      exec 2>&4-
    ;;
    *)
  esac
}


# Demonstration: 

echo "with mute on: "
mute on
ls somefile
ls nofile

mute off
echo "with mute off: "
ls somefile
ls nofile

Result:

$ ./mute.sh
with mute on: 
with mute off: 
somefile
ls: cannot access nofile: No such file or directory