What does /dev/tty do and when should I use it?

0
4
Asked By UserExplorer42 On

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?

3 Answers

Answered By Terminator_99 On

/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.

LearningBash151 -

So, is using /dev/tty a solid strategy, or should we be cautious about it in our scripts?

Answered By BashGuru12 On

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.

SmartScribe88 -

So it's safe to say that using /dev/tty isn't generally recommended, right?

FrustratedBashNovice -

Got it. I thought it was a good approach since I needed clear, user-controlled input. What should I do instead?

Answered By UnixWhiz95 On

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!

BookwormInCode -

What books would you recommend for better understanding this stuff?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.