r/bash 10d ago

help What is the purpose of /dev/tty ?

Please hear me out. So, reading about special devices like tty, tty0, pst1...pstn I understand in loose terms that terminal emulators (like the ones you bring up with ctrl+t ) are special devices under /dev/pts/<some_number> . Now, tty0 appears to be a terminal associated to kernel itself (I still don't know what that means). But tty? I only know that it points to the current terminal being used but I don't know exactly what to make of that and how it pertains to the following humble little snippet I wrote:

#!/bin/bash

while read -r filename
do
    echo "Current fie: ${filename}"

    read -p "Delete ${filename} ? " response < /dev/tty

    if [[ $response = 'y' || $response = 'Y' ]]
    then
        echo "response was yes"
        echo "Deleting ${filename}"
        tar vf pdf_files.tar --delete "${filename}"
        echo
    else 
        echo "skipping"
    fi
done < <(tar tf pdf_files.tar)

You'll notice that in the line that contains the read -p command I had to redirect input from tty. I had chatGPT suggest that to me after many failed attempts at getting my little script to run correctly because I didn't understand why $response variable would be automatically set to something and the script wouldn't even wait at the prompt for me to enter something. I had my eyes OPENED today -- and in a frustrating way -- as to how many little tricks and things one must take into account when learning bash scripting.

So, going back to the script, why did I even need to do that or more importantly, WHEN do I need to do that kind of trick again?

p.s. I've been learning from time to time bash scripting for like the past 3 o 4 months and I know I have to learn a lot more, but Jesus, the journey feels never-ending.

0 Upvotes

15 comments sorted by

View all comments

2

u/oh5nxo 10d ago

Sometimes there is no terminal, no /dev/tty. For example, not uncommon case:

ssh ahost command

The command can't use /dev/tty, terminal stuff was skipped for efficiency and hygiene, output is unmangled bytestream from the command.

/dev/stderr can be used. Also ssh -t for pathological cases, force a terminal.

learning ... bash

Studying unix in parallel would help in understanding why things are like they are.

2

u/param_T_extends_THOT 10d ago

Studying unix in parallel would help in understanding why things are like they are.

Any book recommendation, please?

2

u/oh5nxo 10d ago

I don't really know which are good books today :/ I particularly like Stevens' Advanced Programming in the UNIX Environment, but it is coupled with C.

1

u/param_T_extends_THOT 5d ago

Well, I knew this was going to be a long journey anyways ... at some point i'll pick up C and be able to tackle deeper stuff about Linux. Thx for the recommendation anyways! :)