简体   繁体   English

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

[英]Redirect copy of stdin to file from within bash script itself

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.参考https://stackoverflow.com/a/11886837/1996022 (也无耻地偷了标题),问题是如何捕获脚本的 output 我想知道如何另外捕获脚本输入。 Mainly so scripts that also have user input produce complete logs.主要是这样的脚本也有用户输入产生完整的日志。

I tried things like我尝试过类似的事情

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?也许使用script命令会更容易? You could either have your users run the script with script directly, or do something kind of funky like this:你可以让你的用户直接使用script运行脚本,或者做一些像这样的时髦的事情:

#!/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

Unfortunately, you can't pass a function to script -c which is why the double-call is necessary in this method.不幸的是,您不能将 function 传递给script -c ,这就是为什么在此方法中需要双重调用的原因。

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 调用非面向用户的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>

It's simpler:它更简单:

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

The wonderful thing is your_script can be a function, command or a {} command block!奇妙的是your_script可以是 function、命令或{}命令块!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM