Reading and Writing from the Terminal in a Shell Pipeline
Last updated 07 November 2021
When writing a shell script that might be used in a pipeline, it can
be useful to bypass the rerouting of stdin and stdout to still
interact directly with the user on the terminal. Let’s take a simple
script that lets you pick one of the lines from stdin by number and
then prints it to stdout.
Our first, not working, attempt looks like this:
If you try and run this script you’ll notice you’re never prompted for
input.
The trick is to explicitly read input from /dev/tty by redirecting
stdin when doing read:
This works great now:
But that isn’t actually that useful. You probably want to pipe that
into another command:
When you run it, though, it just hangs with no output. That’s because
all the echos are now going to the pipe instead of to the terminal!
You can use stderr (aka file descriptor 2) for this:
Now when you run it, it behaves as expected:
Hopefully you’ll find this helpful when you do some shell scripting.