Access standard input and output as files

Q I'm trying to write a couple of Bash scripts using utility programs that take keyboard input. For example,

update-alternatives --config xxx

needs a choice from the keyboard. I want to automate it from a parameter passed when the script is used. At the moment my best effort writes a file using the input parameter, runs update-alternatives, redirecting input from the newly created file, then deletes the file. There must be a better way. How can you pass a parameter rather than use keyboard input without writing it to a file first?

A Remember the Linux (and Unix) creed: "Everything is a file." This includes standard input and output. They have the special file handles &0 for stdin and &21 for stdout (&2 is stderr). This should do what you need:

echo "A" | update-alternatives -- config xxx <&0

Where A is the input parameter. echo sends the command to stdout. The pipe (|) sends the stdout to stdin for the next command. &0 is the file handle for stdin, so <&0 redirects it to the command. Another Linux truism applies here too: "There are always at least two ways to accomplish a task." Instead of &0, &1 and &2 you can use /dev/stdin, /dev/stderr and /dev/stdout. The & versions are easier to type for quick shell commands, but the /dev versions will be a little more readable when you look at the script six months from now.

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar