Operating System - Linux
1752274 Members
5108 Online
108786 Solutions
New Discussion юеВ

Re: ctrl-d in while statement

 
SOLVED
Go to solution
Gemini_2
Regular Advisor

ctrl-d in while statement

I want to write a while statement to take user input, until user hit ctrl-d, how do I do that?

thank YOU
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

Re: ctrl-d in while statement

Hi Gemini:

# while read LINE
> do
> echo "I read: ${LINE}"
> done

...to stop, use CTL_D.

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: ctrl-d in while statement

so easy, I complicated the problem.

thank YOU
Mark Greene_1
Honored Contributor

Re: ctrl-d in while statement

This is not generally a good idea. Control-D is usually mapped to EOF; you can do stty -a to see this. Howevery, these values are all change able. For example, it's possible to map control-D to intr (which is usually a control-c) and then you'd have problems.

Having said that, you can do this:

char=""
while [[ $char -ne "^D" ]]
do
.
.
.
stty raw;char=`dd if=/dev/tty count=1 2>/dev/null`;stty -raw
done

and that may work for you.

mark
the future will be a lot like now, only later
Jeff Schussele
Honored Contributor

Re: ctrl-d in while statement

Hi,

I agree with Mark.
Control chars can be problematic - especially for ttytype issues - even sessions themselves.
It's better to use standard alpha ASCII chars like "Q/q" for quit, "E/e" for exit, etc. Even whole words like quit or exit.
These are easily programable with case statements.

My $0.02,
Jeff
PERSEVERANCE -- Remember, whatever does not kill you only makes you stronger!
Bill Hassell
Honored Contributor

Re: ctrl-d in while statement

Another technique is to check that the line is empty (user just pressed CR), something like this:

while read LINE
do
if [ -z "$LINE" ]
then
echo "User entered nothing, exiting..."
exit
fi
...process other $LINE contents...
done

Be sure to quote "$LINE" to properly handle a null input.


Bill Hassell, sysadmin