BrainStone
BrainStone

Reputation: 3155

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. 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.

Upvotes: 2

Views: 514

Answers (2)

Nikita Malyavin
Nikita Malyavin

Reputation: 2107

It's simpler:

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

The wonderful thing is your_script can be a function, command or a {} command block!

Upvotes: 0

John Moon
John Moon

Reputation: 924

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>

Upvotes: 3

Related Questions