-3

I have wrote a shell script in which I would like to include the functionality to exit the program by pressing the q key. Can I do that?

Here is what I currently have:

#!/bin/ksh
echo "Press Q to exit \t\t:\c"
read input 
if [[ $input = "q" ]] || [[ $input = "Q" ]] 
    then exit 1 
else 
    echo "Invalid Input." 
fi
Toby Speight
  • 8,460
  • 3
  • 26
  • 50
Yeshky
  • 25
  • 1
  • 3
  • There's no general way to do that. If you show us your script we can probably tell you what you can achieve and how? – Henrik supports the community May 11 '16 at 06:19
  • It depends what it does but I don't see any benefit in doing that. Why not simply use CTRL-C while you're at it? – Julie Pelletier May 11 '16 at 06:46
  • You could look at using `stty intr q` near the top of the script to "remap" CTRL-C to q. This has the disadvantage that CTRL-C will no longer do anything... If you decide this is an accaeptable approach, you will want to `trap` the SIGINT such that you can reset the mapping using `stty intr ^c` – forquare May 11 '16 at 14:27
  • Thanks Henrik & Julie for your prompt response. Here is my script but it exits if I've entered anyother key otherthan 'q' saying invalid input. I would like to loop the program such that it should again prompt for the input without exiting. #!/bin/ksh echo "Press Q to exit \t\t:\c" read input if [[ $input = "q" ]] || [[ $input = "Q" ]] then exit 1 else echo "Invalid Input." fi – Yeshky May 11 '16 at 16:05

1 Answers1

0

Use while read input, but due to we want to avoid repeat the echo -en "Press Q to exit \t\t: " statement twice, so we better off to use while true instead (a do while variant):

xiaobai:tmp $ cat hello.sh 
#!/bin/ksh
while true; do
    echo -en "Press Q to exit \t\t: "
    read input
    if [[ $input = "q" ]] || [[ $input = "Q" ]] 
        then break 
    else 
        echo "Invalid Input."
    fi
done
xiaobai:tmp $ ./hello.sh 
Press Q to exit                 : apple
Invalid Input.
Press Q to exit                 : q
xiaobai:tmp $ 
林果皞
  • 4,946
  • 2
  • 29
  • 45