从bash脚本本身将stdin的副本重定向到文件 [英] Redirect copy of stdin to file from within bash script itself

查看:86
本文介绍了从bash脚本本身将stdin的副本重定向到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考 https://stackoverflow.com/a/11886837/1996022 (也毫不掩饰地偷了标题)问题是如何捕获脚本的输出,我想知道如何另外捕获脚本的输入.主要是因为这些脚本还具有用户输入的内容,因此可以生成完整的日志.

In reference to https://stackoverflow.com/a/11886837/1996022 (also shamelessly stole the title) where the question is how to capture the script's output I would like to know how I can additionally capture the scripts input. Mainly so scripts that also have user input produce complete logs.

我尝试过类似的事情

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

但是似乎没有任何效果.我可能只是想念一些东西.

But nothing seems to work. I'm probably just missing something.

推荐答案

也许使用

Maybe it'd be easier to use the script command? You could either have your users run the script with script directly, or do something kind of funky like this:

#!/bin/bash

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

if [ "$1" = "--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 "$0 --log $*" test.log
fi

不幸的是,您无法将函数传递给script -c,这就是为什么在此方法中必须进行两次调用的原因.

Unfortunately, you can't pass a function to script -c which is why the double-call is necessary in this method.

如果可以使用两个脚本,也可以使用一个面向用户的脚本,该脚本仅使用script调用非面向用户的脚本:

If it's acceptable to have two scripts, you could also have a user-facing script that just calls the non-user-facing script with 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>

这篇关于从bash脚本本身将stdin的副本重定向到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆