DEV Community

Cover image for Redirect with exec Command
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Redirect with exec Command

This article was originally published on bmf-tech.com.

Overview

The exec command replaces the current process with a command, but when used without arguments, it allows for dynamic changes to redirection.

This was prompted by the code that appeared when confirming at the prompt during direct push to master:

#!/bin/sh
eval < /dev/tty
read ANSWER
Enter fullscreen mode Exit fullscreen mode

I didn't quite understand it, so I looked it up.

Usage

#!/bin/sh
echo "Output to stdout" // Standard input
exec > redirect.txt // Change file descriptor
echo "Output to file" // Output to file
Enter fullscreen mode Exit fullscreen mode

The code that appeared during direct push to master is:

#!/bin/sh
exec < /dev/tty
read ANSWER
Enter fullscreen mode Exit fullscreen mode

This passes the input from the current terminal (/dev/tty) to the standard input of the exec command. (It's a bit confusing...)

Thoughts

It seems useful when you can't read from standard input for some reason.

References

Top comments (0)