What does /dev/tty do and when should I use it?
Asked by
!branchFix
I've been diving into bash scripting and came across the device /dev/tty. I know that terminal emulators like what you get with Ctrl+T are special devices under /dev/pts/. I get that tty0 is tied to the kernel, but I'm confused about the purpose of /dev/tty itself. In a script I wrote, I used a read command which redirected input from /dev/tty. I tried without it, and my variable didn't get set correctly. I want to understand the role of /dev/tty better and when it's actually useful in scripting. How does it relate to user input, especially when using other commands like tar?
Answers
Sometimes you might not even have access to /dev/tty, like when executing commands over ssh. In those cases, the command canโt rely on using /dev/tty, which is why itโs important to understand alternative outputs and error handling. When youโre in interactive or local contexts, using /dev/tty has its place, but beware of where you're calling your scripts from!
Reply to this answer
You were tripped up because you were trying to read from both tar's output and inputting responses from the terminal, which essentially is why your script wasnโt working. When you use read from /dev/tty, it explicitly tells the script to expect input from the terminal itself, avoiding those conflicts. You could also try using different file descriptors to separate those input streams for more complex scenarios. Though, honestly, many seasoned users would say you don't *need* to read from /dev/tty; itโs often considered messy and maybe not even POSIX compliant.
+riddle me this~: So it's safe to say that using /dev/tty isn't generally recommended, right?
after the whistle: Got it. I thought it was a good approach since I needed clear, user-controlled input. What should I do instead?
Reply to this answer
/dev/tty can be used in lots of scenarios in bash. It's there to access the terminal associated with your current session. For instance, when you want to ensure that output or error messages show up right on the terminal and not get redirected elsewhere, using /dev/tty can be your best friend. A use-case could be something like this: `cat files* | awk -f script | tee /dev/tty | sort > output`. It's all about making sure you're getting the right information displayed on your terminal when working with multiple input streams.
SiltTrap: So, is using /dev/tty a solid strategy, or should we be cautious about it in our scripts?
Reply to this answer
Add your answer
Answers are reviewed before publication.
~!lunch is ready: What books would you recommend for better understanding this stuff?