With Bash Scripting, how can I suppress all output

2019-01-04 15:32发布

I have a bash script that runs a program with parameters. That program outputs some status (doing this, doing that...). There is no option for this program to be quiet. How can I prevent the script from displaying anything?

I am looking for something like windows "echo off".

7条回答
Luminary・发光体
2楼-- · 2019-01-04 16:10

Take a look at this example from The Linux Documentation Project:

3.6 Sample: stderr and stdout 2 file

This will place every output of a program to a file. This is suitable sometimes for cron entries, if you want a command to pass in absolute silence.

     rm -f $(find / -name core) &> /dev/null 

That said, you can use this simple redirection:

/path/to/command &>/dev/null
查看更多
老娘就宠你
3楼-- · 2019-01-04 16:13

The following sends standard output to the null device (bit bucket).

scriptname >/dev/null

and if you also want error messages to be sent there, use one of (the first may not work in all shells):

scriptname &>/dev/null
scriptname >/dev/null 2>&1
scriptname >/dev/null 2>/dev/null

and, if you want to record the messages but not see them, replace /dev/null with an actual file, such as:

scriptname &>scriptname.out

For completeness, under Windows cmd.exe (where "nul" is the equivalent of "/dev/null"), it is :

scriptname >nul 2>nul
查看更多
淡お忘
4楼-- · 2019-01-04 16:13

Try

: $(yourcommand)

: is short for "do nothing".

$() is just your command.

查看更多
家丑人穷心不美
5楼-- · 2019-01-04 16:17

In you script you can add the following to the lines that you know are going to give an output:

some_code 2>>/dev/null

Or else you can also try

some_code >>/dev/null
查看更多
干净又极端
6楼-- · 2019-01-04 16:26

Something like

script > /dev/null 2>&1

This will prevent standard output and error output, redirecting them both to /dev/null.

查看更多
Summer. ? 凉城
7楼-- · 2019-01-04 16:32

An alternative that may fit in some situations is to assign the result of a command to a variable:

$ DUMMY=`grep root /etc/passwd`
$ echo $?
0
$ DUMMY=`grep r00t /etc/passwd`
$ echo $?
1

Since Bash and other POSIX commandline interpreters does not consider variable assignments as a command, the present command's return code is respected.

查看更多
登录 后发表回答