Operating System - Linux
1747984 Members
4551 Online
108756 Solutions
New Discussion юеВ

Can I perform a "read" command from inside a "while read line" loop

 
SOLVED
Go to solution
John Hall
Frequent Advisor

Can I perform a "read" command from inside a "while read line" loop

The following script processes (reads) every other line from my "/etc/passwd" file:


while read LINE
do
USERID=`cut -d: -f1`
read DUMMY?"Delete user $USERID ?"
case $DUMMY in
Yes) userdel -r $USERID ;;
esac
done < /etc/passwd


Is there no way to use the "read DUMMY" inside a while loop that is reading lines from a file?
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor

Re: Can I perform a "read" command from inside a "while read line" loop

Yes, but you will not be able to read from stdin since that is already redirected.

while read LINE
do
USERID=$(cut -d: -f1)
echo "Delete user ${USERID}? (Yes/No) \c"
read DUMMY < /dev/tty
case ${DUMMY} in
Yes) userdel -r ${USERID} ;;
esac
done < /etc/passwd

/dev/tty is the current terminal device.

It would probably be a good idea to add this test BEFORE your while loop.

if [[ ! -t 0 ]]
then
echo "${0}: Not an interactive session" >&2
exit 255
fi

so that you do not execute your script in a non-interactive environment.



If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor
Solution

Re: Can I perform a "read" command from inside a "while read line" loop

Hi John:

You need separate file descriptors. This is one variation:

#!/usr/bin/sh
exec 3<&0
while read LINE
do
USERID=`echo ${LINE}|cut -d: -f1`
echo "Delete user $USERID ?"
read -u3 DUMMY
case $DUMMY in
Yes) userdel -r $USERID ;;
esac
done < /etc/passwd

Regards!

...JRF...
John Hall
Frequent Advisor

Re: Can I perform a "read" command from inside a "while read line" loop

Thanks guys! The "read -u3 DUMMY" is cleaner since I do not have to test to see what the terminal device is. However, I always like to know 2 ways to do everything so the "< /dev/tty" is helpful also.