将标准输入的副本从 bash 脚本本身重定向到文件

Redirect copy of stdin to file from within bash script itself

参考 (也无耻地盗用了标题),其中的问题是如何捕获脚本的输出我想知道如何另外捕获脚本输入。主要是让也有用户输入的脚本产生完整的日志。

我试过

exec 3< <(tee -ia foo.log <&3)
exec <&3 <(tee -ia foo.log <&3)

但似乎没有任何效果。我可能只是遗漏了一些东西。

也许使用 script 命令更容易?您可以让您的用户 运行 直接使用 script 脚本,或者做一些像这样时髦的事情:

#!/bin/bash

main() {
    read -r -p "Input string: "
    echo "User input: $REPLY"
}

if [ "" = "--log" ]; then
    # If the first argument is "--log", shift the arg
    # out and run main
    shift
    main "$@"
else
    # If run without log, re-run this script within a
    # script command so all script I/O is logged
    script -q -c "[=10=] --log $*" test.log
fi

不幸的是,您不能将函数传递给 script -c,这就是为什么在此方法中需要双重调用的原因。

如果有两个脚本是可以接受的,您还可以有一个面向用户的脚本,它只使用 script:

调用非面向用户的脚本
script_for_users.sh
--------------------
#!/bin/sh
script -q -c "/path/to/real_script.sh" <log path>
real_script.sh
---------------
#!/bin/sh
<Normal business logic>

更简单:

#! /bin/bash
tee ~/log | your_script

奇妙的是your_script可以是函数、命令或{}命令块!