gpt4 book ai didi

linux - 无法使用脚本将交互式 shell 的输出重定向到文件

转载 作者:太空宇宙 更新时间:2023-11-04 12:43:26 25 4
gpt4 key购买 nike

我正在尝试编写简单的输出记录器。它只是拒绝工作。我可以发誓,它成功了一次,而且非常漂亮。

这是实践,所以我不想使用预构建的 bash 工具。 (如脚本)

代码:

#!/bin/bash
# create_log.sh

exec 6>&1

exec &> log

s

a=0

while true
do
sleep 1

echo love

((a++))
if [ "$a" -eq 1000 ]
then
break
fi

done

exec 1>&6 6>&-

echo "Stopped doing love"

我在控制台 中运行这个脚本。/create_log.sh &

只要循环结束,stdoutstderr 就应该被重定向到日志文件。但他们根本没有。

充满的日志文件,但我就是无法获取日期。 (或控制台的任何其他输出)

附言如果我只是在控制台中键入 exec > log,它就可以正常工作。

最佳答案

方法需要在您打算为其重定向输出的 shell 中本地运行,而不是在该 shell 的任何子进程中运行。运行任何带有 & 的命令作为将它与下一个命令分开的命令将它放在子进程中,而不是在 shell 本身中运行。

考虑这对函数(对于 bash 4.1 或更新版本):

# for this example, consider this content to belong to file-with-functions.bash

start_redir() {
exec {orig_stdout}>&1
exec > >(tee log >&$orig_stdout)
}

end_redir() {
[[ $orig_stdout ]] || {
echo "Not redirected with start_redir previously" >&2
return 1
}
exec 1>&$orig_stdout
exec {orig_stdout}>&-
}

...这可以按如下方式使用:

. ./file-with-functions.bash # source these functions into the current shell; no &

start_redir
ls
end_redir

您可以将这些函数放在您获取的文件中,但是需要在前台 中完成获取,因为将任何东西放在后台都会使它发生在子进程中,而不是您的 shell正在使用它自己。

关于linux - 无法使用脚本将交互式 shell 的输出重定向到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39495734/

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