I have a script. I would like to give this script a quiet mode and a verbose mode.
This is the equivalent of:
if $verbose
then
redirect="> /dev/null"
fi
echo "Verbose mode enabled" $redirect # This doesn't work because the redirect isn't evaluated.
I'd really like a better way of doing this than writing if-elses for every statement affected.
eval could work, but has obvious side effects on other variables.
You can send output to /dev/null, by using command >/dev/null syntax. However, this will not work when command will use the standard error (FD # 2). So you need to modify >/dev/null as follows to redirect both output and errors to /dev/null.
The way we can redirect the output is by closing the current file descriptor and then reopening it, pointing to the new output. We'll do this using the open and dup2 functions. There are two default outputs in Unix systems, stdout and stderr. stdout is associated with file descriptor 1 and stderr to 2.
If any other file were given instead of /dev/null, the standard output would have been written to that file. Similarly, to redirect only the STDERR to /dev/null, use the integer '2' instead of '1' .
Redirection is done using either the ">" (greater-than symbol), or using the "|" (pipe) operator which sends the standard output of one command to another command as standard input. As we saw before, the cat command concatenates files and puts them all together to the standard output.
You could write a wrapper function:
redirect_cmd() {
# write your test however you want; this just tests if SILENT is non-empty
if [ -n "$SILENT" ]; then
"$@" > /dev/null
else
"$@"
fi
}
You can then use it to run any command with the redirect:
redirect_cmd echo "unsilenced echo"
redirect_cmd ls -d foo*
SILENT=1
redirect_cmd echo "nothing will be printed"
redirect_cmd touch but_the_command_is_still_run
(If all you need to do is echo with this, you can of course make the function simpler, just echoing the first argument instead of running them all as a command)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With