Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let be the files com and fic whith the access rights defined in the following shell sequence:

$ cat com
if tty>/dev/null
    then read x
    else read x<fic
fi
echo $x
$ cat fic
abcd
$ ls -l com fic
-r-xr-xr-x  1 jmr    ens    70 Jan 22 09:41 com
-r--r--r--  1 jmr    ens    5 Jan 22 09:41 fic
$

Why does it stops at echo $x when com is launched (in foreground)? Shouldn't it read fic then?

share|improve this question
2  
Where are you trying to run com? – Eric Renouf Jan 4 at 17:52
    
on a table with a sheet of paper and a pencil, this is the answer given by the book: Exercices corrigés de programmation UNIX by J.M. Rifflet – Marine1 Jan 4 at 17:56
1  
Also, when you launch com in the foreground it will have a tty, so will be in the if block, not the else so it will wait for input on stdin, if you execute it without a tty (for example ssh localhost ./com) it will read fic – Eric Renouf Jan 4 at 17:56
2  
Strictly speaking, unless an error happens, the last line will be echo $x, either way. Your question is probably "why is the script does not stop on the interactive read?" – 9000 Jan 4 at 17:57
    
Yes, that's pretty much my question... – Marine1 Jan 4 at 17:58
if tty>/dev/null ; then
    read x
else
    read x<fic
fi

means, that fic will only be read when tty returns an error. Which will happen when it finds that its stdin is not a terminal. Typically this happens either when the script is in a pipe or when you run it via nohup, or as a cron job, or remotely via ssh -T...

Using [ -t 0 ] as a condition is pretty much the same (and faster, since [ aka test is usually a built-in these days).

share|improve this answer

The com shell script, when executed in the foreground, stops on line: read $x because it is waiting for an input on read on the actual tty.

If you type a line, the read will terminate and set this line to the variable x.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.