我的 bash 文件中有几个脚本,它们应该执行某些任务,例如......
#!bin/bash
yum -y update
service restart nginx
yum install atop
cat /var/log/somelog.log > /home/cron/php/script
它一直持续着,但问题是,执行每个任务时,bash 都会向我显示输出。例如 service restart nginx
,输出一些消息。我想隐藏所有这些消息。通常公认的实现这一目标的方法是什么?因为,我正要将 STDOUT 重定向到/dev/null
,但是考虑到我有超过 50 个连续任务要运行,这意味着我必须执行/dev/null
这么多任务,出于某种原因,这对我来说似乎效率不高。
答案1
将所有输出重定向为一个块。
(
yum -y update
service restart nginx
yum install atop
cat /var/log/somelog.log > /home/cron/php/script
) > /dev/null 2>&1
答案2
您可以保存 stdout 和 stderr 的文件描述符,覆盖它们,并在程序运行后恢复它们:
exec 3>&1
exec 4>&2
exec 1>/dev/null
exec 2>/dev/null
./script-1
./script-2
...
./script-n
exec 1>&3
exec 2>&4
# delete the copies
exec 3>&-
exec 4>&-
答案3
如果您想隐藏正在运行的命令的所有输出(包括输出和错误),但仍然能够自己打印消息,那么 Hauke Laging 的方法绝对是正确的方法。
它允许您保留对 stdout(又名文件描述符 1)和 stderr(又名文件描述符 2)的引用,将它们重定向到 /dev/null,但如果您希望显示消息,仍然使用它们。我只想添加一些评论来准确解释它在做什么。
exec 3>&1 # Open file descriptor 3, writing to wherever stdout currently writes
exec 4>&2 # Open file descriptor 4, writing to wherever stderr currently writes
exec 1>/dev/null # Redirect stdout to /dev/null, leaving fd 3 alone
exec 2>/dev/null # Redirect stderr to /dev/null, leaving fd 4 alone
# Programs won't show output by default; they write to fd 1 which is now /dev/null.
# This is because programs inherit file descriptors from the shell by default.
echo foo
# You can choose to show messages by having them write to fd 3 (old stdout) instead.
# This works by saying that echo's fd 1 (stdout) is the shell's fd 3.
echo bar >&3
# And when you're done you can reset things to how they were to start with
exec 1>&3 # Point stdout to where fd 3 currently points (the original stdout)
exec 2>&4 # Point stderr to where fd 4 currently points (the original stderr)
exec 3>&- # Close fd 3 (it now points to the same spot as fd 1, so we don't need it)
exec 4>&- # Close fd 4 (it now points to the same spot as fd 1, so we don't need it)
如果您要在任何大小的脚本中使用它,并且您经常需要打印有关事情进展情况的状态更新,您可能需要创建辅助函数来将echo "$@" >&3
消息echo "$@" >&4
打印到原始文件stdout 和 stderr,因此您不必在脚本中&3
添加引用。&4
和这个 bash-hackers.org 重定向教程是一个很好的视觉描述,说明了像这样的中等复杂的重定向实际上是如何工作的。