Hi Dave. I’m trying to create a shell script in HP-UX Unix that looks like this:
while read usrname do lsh $usrname done < $file
and in lsh I added some error checks. If one occurs I ask the user to correct their input, but the code didn’t work that way and it continues to read another line from file usrname. I don’t know how to stop in while loop, to get input from the user. What’s the trick?
This is a classic shell scripting question because once you redirect standard input to be from a file (as you do with the < $file after the done statement) then subshells, functions and everything else also inherit the changed file descriptor.
The good news is that the solution is straightforward: just change standard input (stdin for you Unix geeks out there) to the keyboard, aka “/dev/tty”. Here’s a simple little script that demonstrates what I’m talking about:
while read text
do
if [ “$text” = “fi” ] ; then
echo -n ‘saw FI, need something else: ‘
read newinput < /dev/tty
echo new input. Read $newinput
else
echo “> ” $text
fi
done < $1
It’s obviously not exactly what you have, but you can see how you can use the redirect in the while loop to pull input from a file (in this case I’m using $1 for simplicity). and then notice how the read statement has an input redirect too: < /dev/tty.
Try that with your application and see if it works out!
Avid shell script programmers will doubtless be psyched to learn more about my best-selling Wicked Cool Shell Scripts, a collection of over 100 fun and educational shell scripts.
Hi Dave, I’m new to the Linux environment and trying to develop an embedded app in C on a Digi cc9p9215. I wish to include a dedicated monitor/control via telnet but have hit a road block. I can establish a connection on a port other than 23, but when I try to use port 23 I cannot bind because the address is already in use (by the OS) How can I redirect the connection on port 23 so that instead of dropping into the OS prompt, it is picked up by the telnet task in my program? I believe I can use a redirect in “shells” but I have been struggling with this for a couple of weeks now! Any pointers would be VERY welcome. Thanks.
dj, it’s because /dev/tty isn’t the same as /dev/console. On most Linux systems (as I recall) the console gets its own device driver. Try redirecting INPUT like this:
read variable < /dev/tty
then
read variable < /dev/console
and see what happens.
What if the input is coming from the terminal and you want to see the prompt and printf at the terminal (see below), but when the command was issued on the console it redirected stdout and stderr, like:
===> cmd 1>t1 2>t2
read -rep “Input y/n: ” newinput
printf “You responded: %s\n” “${newinput}”
What I’ve done is redirect both, &>/dev/tty, but I’m not understanding exactly why it works. Thoughts…
You are a GOD! Thanks so much for this. I’ve been stuck on this exact problem for days.
Sandra Martin
New interesting theme