Is this a tty?

That is a funny question to ask if you are a human (because you *should* know the answer). But it is not that dumb for a system. As a matter of fact, among the multiple tests the shell admits (man 1 test), there is a -t which serves specifically for that:

$ test -t 0

returns 0 (that is, success or true in shell jargon) if the standard input (file descriptor 0) is open and is associated with a terminal. So, unless things are going pretty bad, the following

$ test -t 0 && echo $?

Should always print a 0.

However, when a file may be run in both interactive and non-interactive environments, the above test is not just useful but sometimes even necessary. Assume you want to automatically run screen when you log into your session. You might think of adding the following line

$ screen -d -R

to your .profile file. This is OK as long as your cron jobs do not need to use it. But if they need, you are bound to get errors, strange mails or even lost connections. This is because each time a cron job needs a shell, it will read (and execute) the .profile file and, bang! there go your screens et al.

To prevent that from happening, you need to tell the shell to run the line only when in interactive mode. To test this, simply check for the ‘terminal-‘ness of stdin (that is, test -t 0).

In summary, one of the proper ways to automatically run screen when you log in is:

$ cat < .profile
(... snapped ...)
if [ -t 0 ] ; then
    screen -d -R

Which can be also written:

$ cat < .profile
(... ...)
[-t 0] && screen -d -R

but is less human-friendly. For me.

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields