Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Timed read Prompt 1

Status
Not open for further replies.

Michael42

Programmer
Oct 8, 2001
1,454
US
Hello,

In a Bourne shell script if I am prompting a user using a read command, if the user does not enter anything for a set number of seconds (say 15) how can I "escape" the read prompt?

Thanks,

Michael42
 
This should work...
Code:
#!/bin/sh

OLDSTTY=`stty -g`

stty -icanon min 0 time 150

echo "Enter something: \c"

read TEST

stty "${OLDSTTY}"

echo
echo "TEST=${TEST}"
Keep in mind there is a limit to how long some terminals can wait. I think something like 25 seconds or so.

Hope this helps.
 
If you want to do that in Korn shell, you can't use read directly for timed reads as ksh ignores your modified stty settings when reading from terminal.

However this works:

Code:
#!/bin/ksh

OLDSTTY=`stty -g`
stty -icanon min 0 time 150 # read at least zero chars
                            # wait up to 15s for user to type something

echo "Enter something: \c"
line | read TEST junk       # reads the users input line (possible null string)
                            # divides the line: first word goes into TEST variable
                            # the rest of the line is ignored (junk variable) 

stty "${OLDSTTY}"

echo
echo "TEST=${TEST}"


HTH,

p5wizard
 
He said he was writing a Bourne shell script so I gave him a Bourne shell solution.

And it does work in the Korn shell on my system on Solaris 8.
 
I know he specified bourne, I just wanted to try it out in ksh on AIX and it didn't work, so I tried to find out why - that's all.


HTH,

p5wizard
 
Note: if you put your shell in "set -o vi" or some other history editing mode, ksh overrides whatever stty mode you set, and your bourne shell solution won't work in Korn shell.

Also you might want to set a trap for some signals in order to reset the stty settings or risk being logged out after the timeout expires when you exit the script without first running stty ${OLDSTTY} ...

Code:
#!/bin/sh

OLDSTTY=`stty -g`

trap "stty ${OLDSTTY};exit" 0 1 2 3 15

stty -icanon min 0 time 150

echo "Enter something: \c"

read TEST

stty "${OLDSTTY}"

echo
echo "TEST=${TEST}"



HTH,

p5wizard
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top