如何抑制命令的输出?

时间:2014-01-23 19:28:15

标签: bash shell

我想在我的shell脚本中运行一些命令但是想知道一些方法,它什么也不返回。

示例:

#! / bin / bash]
rm / home / user

return: rm: can not lstat `/ home / user ': No such file or directory

我会让命令无形地运行而不返回!

2 个答案:

答案 0 :(得分:4)

要抑制命令的标准输出,传统方法是使用somecommand arg1 arg2 > /dev/null将输出发送到空设备。为了抑制错误输出,可以将标准错误重定向到同一位置:somecommand arg1 arg1 > /dev/null 2>&1

答案 1 :(得分:1)

您的直接错误来自路径中的错误间距,路径中的rm /home/whatever应该没有空格,假设您在目录名称中没有实际空格(在这种情况下,您需要引用或正确逃脱)

关于抑制输出。重定向stdout在这里有点奇怪。

$ touch test.txt
$ rm test.txt > /dev/null 2>&1

^ interactive rm is actually asking if you really want to delete the file here, but not printing the message

如果您只是想获取错误消息,只需将stderr(文件描述符2)重定向到/ dev / null

$ rm test.txt 2> /dev/null

$ rm test.txt 2>&-

如果您希望它不提示do you really want to delete输入消息,请使用强制标记-f

$ rm -f test.txt 2> /dev/null

$ rm -f test.txt 2>&-

要删除您想要rmdir的目录,如果该目录为空或使用递归-r标记,则会删除所有内容 / home / user,这样您就可以了这里需要小心。

除非你让它以--verbose模式运行,否则我无法想到它需要关闭rm命令的stdout。

同样在bash 4中,如果你想将stdout和stderr重定向到同一个位置,只需使用rm whatever &> /dev/null或类似的东西

相关问题