Redirect copy of stdin to file from within bash script itself

爱⌒轻易说出口 提交于 2020-06-27 17:11:42

问题


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.

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.


回答1:


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

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

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>


来源:https://stackoverflow.com/questions/62291762/redirect-copy-of-stdin-to-file-from-within-bash-script-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!