gpt4 book ai didi

bash - bash 中的条件重定向

转载 作者:行者123 更新时间:2023-11-29 08:44:40 25 4
gpt4 key购买 nike

我有一个 bash 脚本,我想在没有附加 tty 的情况下运行时保持安静(比如来自 cron)。我现在正在寻找一种在一行中有条件地将输出重定向到/dev/null 的方法。这是我的想法的一个例子,但我将有更多的命令在脚本中输出

#!/bin/bash
# conditional-redirect.sh
if tty -s; then
REDIRECT=
else
REDIRECT=">& /dev/null"
fi
echo "is this visible?" $REDIRECT

不幸的是,这不起作用:

$ ./conditional-redirect.sh
is this visible?
$ echo "" | ./conditional-redirect.sh
is this visible? >& /dev/null

我不想做的是复制带重定向或不带重定向变体中的所有命令:

if tty -s; then 
echo "is this visible?"
else
echo "is this visible?" >& /dev/null
fi

编辑:

如果解决方案能为我提供一种在“安静”模式下输出某些内容的方法,那就太好了,例如当出现问题时,我可能希望从 cron 获得通知。

最佳答案

对于 bash,您可以使用以下行:

exec &>/dev/null

从那时起,这会将所有 stdoutstderr 定向到/dev/null。它使用 exec 的非参数版本。

通常,exec xyzzy 之类的程序会将当前进程中的程序替换为新程序,但您可以使用此非参数版本来简单地修改重定向,同时保留当前程序。

因此,在您的特定情况下,您可以使用如下内容:

tty -s
if [[ $? -eq 1 ]] ; then
exec &>/dev/null
fi

如果您希望丢弃大部分输出但仍想输出一些内容,您可以创建一个新的文件句柄来实现。像这样的东西:

tty -s
if [[ $? -eq 1 ]] ; then
exec 3>&1 &>/dev/null
else
exec 3>&1
fi
echo Normal # won't see this.
echo Failure >&3 # will see this.

关于bash - bash 中的条件重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com