LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash script to read CTRL+D (https://www.linuxquestions.org/questions/programming-9/bash-script-to-read-ctrl-d-495069/)

panchosansa 10-24-2006 05:07 AM

bash script to read CTRL+D
 
Hello,

I am trying to make a small script that exits the program when it encouters CTRL+D. I've tried things like

Code:

while [[ $in != "^D" ]]
read in
echo $in

Code:

while [[ $in != EOF ]]
Code:

while [[ $in != $EOF ]] //this one termitated the program right away
but with no success. I was also considering making 0x04 a condition in the loop but couldn't find a way to do this. I would be grateful if anyone can tell me how to make this thing work.

unSpawn 10-24-2006 07:56 AM

I am trying to make a small script that exits the program when it encounters CTRL+D
That's logout (signal 1 IIRC) but you can't catch that because it's not a means to end the script. To catch a signal use the Bash "trap" builtin as in "trap 'echo trapped exit, logout or interrupt' 0 1 2".

panchosansa 10-24-2006 09:02 AM

Thanks unSpawn, I wasn't aware that this is the way it should be done. I've tried it and it works but not exactly as I want it to. The segment that I'm using is
Code:

trap "echo trapped" 0 1 2
read input
echo $input

and this works more or less fine. One problem is that I have to enter CTRL+D twice so that the program logouts and the second thing is that it exits also on return and that's something I would like to avoid. Am I doing sth wrong or is it just the way the trap works? Is it possible to have the program logout on CTRL+D and not logout on return.

ta0kira 10-24-2006 10:53 AM

Code:

cat | while read line; do
  #script actions using $line
done

Something like that? [Ctrl]+D is merely a manual EOF when typing to standard input; you will get the same result when the end of a file is reached or a pipe is closed. When not piping input to the script, the standard input file is the console, and [Ctrl]+D closes the input side of that file.
ta0kira

bigearsbilly 10-25-2006 03:49 AM

set -o ignoreeof

in your profile

panchosansa 10-26-2006 03:25 AM

Thanks for your help everyone. I ended up using unSpawn suggestions and it suits me fine though it is not exactly waht I was looking for.

Regards,
V


All times are GMT -5. The time now is 04:29 PM.