> "$logfile",其中 log 是一个函数在“库”中-6ren">
gpt4 book ai didi

bash - 在不使用 stderr 的情况下将 stdout 重定向到文件后写入终端?

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

我有两个 shell 脚本,一个用作主要“程序”,另一个用作“库”。

在“程序”的几个地方,我会做类似这样的事情:log "$thing">> "$logfile",其中 log 是一个函数在“库”中定义。

# program.sh

logfile="log.txt"
stuff="hahah heheh hoho"

. library.sh

for thing in $stuff; do
log "$thing" >> "$logfile"
done

我的问题:有没有一种方法可以将函数的一些输出重定向回终端而不使用stderr

# library.sh

log () {

# This gets written to the log
echo "`date --rfc-3339=seconds`: $1"

# How to write this to the terminal *without* using stderr?
echo "Info: Message written to log." >&2

}

我想避免使用 stderr 因为在我的实际程序中,有一个选项可以将错误重定向到一个文件,但是我想发送到终端的消息是信息性的,而不是错误,并且应该始终显示在终端上。

最佳答案

在另一个 FD 上打开 /dev/tty

exec 0< /dev/null
exec 1> /dev/null
exec 2> /dev/null
exec 3> /dev/tty
echo 'Hello, World!' >&3

关于bash - 在不使用 stderr 的情况下将 stdout 重定向到文件后写入终端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9405200/

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