Search code examples
bashstdoutstdin

Redirect stdout and stdin to file


I can write to and read from a file:

echo a > b.txt
read c < b.txt

Is Bash able to do this implicitly? Something like:

<turn on implicit mode>
echo a
read c
<turn off implicit mode>

While “implicit mode” is on, all stdout goes to b.txt and all stdin reads from b.txt. I tried:

exec > b.txt

but it only affects stdout.


Solution

  • Working off the responses here, I came up with this:

    d=`tty`
    exec >b.txt <b.txt
    echo a
    read c
    exec >$d <$d
    

    I also realized that it might be better to leave stdout and stdin alone:

    exec 3>b.txt 4<b.txt
    echo a >&3
    read c <&4