Reputation: 6894
I'm trying to read user input which has a default value set but when I do a echo the data is not printed
#!/bin/sh
ROUTETOCOM="n"
read -t 4 -p "Route data from Port? [y/n] : " ROUTETOCOM
echo $ROUTETOCOM
If the user dosen't key in any value within 4 seconds echo $ROUTETOCOM is not displaying 'n' What is wrong with the script?
Upvotes: 2
Views: 681
Reputation: 295403
If you want to apply a default, do that after the fact:
read -t 4 -p "Route data from Port? [y/n] : " route_toggle
: "${route_toggle:=n}"
See also the Bash-Hackers' Wiki page on parameter expansion -- particularly, the sections on using a default value or assigning a default value.
The documentation for read -t
follows (for bash 3.2):
The
-t
option causes read to time out and return failure if a complete line of input is not read within TIMEOUT seconds. If the TMOUT variable is set, its value is the default timeout. The return code is zero, unless end-of-file is encountered, read times out, or an invalid file descriptor is supplied as the argument to -u.
Or, for bash 4.3:
-t timeout
- time out and return failure if a complete line of input is not read within TIMEOUT seconds. The value of the TMOUT variable is the default timeout. TIMEOUT may be a fractional number. If TIMEOUT is 0, read returns immediately, without trying to read any data, returning success only if input is available on the specified file descriptor. The exit status is greater than 128 if the timeout is exceeded
No part of either version of this documentation expresses or implies that a timeout will not cause the value to be changed; the only guarantee is that the return code will not be zero in the event that a timeout takes place.
Upvotes: 5