Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally redirect the output of a command to /dev/null?

Tags:

redirect

bash

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.

like image 902
Lawrence Johnston Avatar asked Mar 25 '10 23:03

Lawrence Johnston


People also ask

How do you redirect output of a command to dev Null?

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.

How do you redirect a process of output?

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.

How do I redirect only stderr to dev Null?

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' .

How do I redirect the output of a command in Linux?

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.


1 Answers

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)

like image 125
Cascabel Avatar answered Oct 04 '22 15:10

Cascabel