简体   繁体   English

为什么在终端中没有任何输出的情况下我不能在Linux中执行某些命令?

[英]Why can't I execute some command in Linux without any output in the terminal?

I tried to execute "rmdir * " in terminal. 我试图在终端中执行“ rmdir *”。 Because some are not directories under current folder, error messages showing some files are not directory will show. 由于有些不是当前文件夹下的目录,因此将显示错误消息,提示某些文件不在目录中。 My goal is to execute the command silently without any output. 我的目标是无提示地静默执行命令。

I tried the following: 我尝试了以下方法:

rmdir * > /dev/null
rmdir * > file.txt
rmdir * |grep "noexist"  (some non-existing characters)
rmdir * 2>&1 > /dev/null
rmdir * 2>&1 > file.txt
rmdir * 2>&1 |grep "noexist"

Only the last command works! 只有最后一个命令有效! I feel a little confused. 我感到有些困惑。 As the last command works, why don't the 4th and 5th commands work? 当最后一个命令起作用时,为什么第四个和第五个命令不起作用?

> redirects STDOUT. >重定向STDOUT。 2> redirects STDERR. 2>重定向STDERR。 &1 redirects to STDOUT. &1重定向到STDOUT。 | transfers STDOUT to STDIN for the new process. 将STDOUT转移到STDIN以进行新过程。

Did you try: 你试过了吗:

rmdir * > /dev/null 2> /dev/null

Which redirects both STDOUT and STDERR to the null device. 它将STDOUT和STDERR都重定向到空设备。

1) Doesn't redirect stderr using 2>...
2) See 1.
3) See 2.
4) Redirects stderr to stdout, and stdout is redirected to /dev/null, so you still see the redirected stderr on stdout.
5) See 4. The file to which stdout is redirected is just different.
6) This works because you redirected stderr to stdout. stdout is piped in to grep as grep's stdin.

What REALLY works: 真正起作用的是:

rmdir * >/dev/null 2>&1

Why does that work? 为什么行得通? Because first stdout was redirected to /dev/null. 因为第一个标准输出被重定向到/ dev / null。 Then stderr was redirected to stdout, which was already redirected to /dev/null. 然后将stderr重定向到stdout,而该stdout已经重定向到/ dev / null。

除非目录为空,否则您不能使用rmdir。确保执行此操作之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM