Stop a shell script by pressing a button

I have this shell script which is supposed to run normally and stop when I press q button:

while true; do echo "hello" read -t 0.25 -N 1 input if [[ $input = "q" ]] || [[ $input = "Q" ]]; then break fi
done

When I run it, I get this output that keeps being displayed continuously:

hello
script.sh: 3: read: Illegal option -t
script.sh: 4: script.sh: [[: not found
script.sh: 4: script.sh: [[: not found

But when I press on q button, it does not stop. It keeps running till I stop it using Ctrl + c.
Any suggestions to fix this?

1 Answer

I've just tried on my Ubuntu 16.04 system and it works correctly.

What I've found is, that if you use a generic sh instead of bash, it won't work giving out the error

read: Illegal option -t

Make sure that your script begins with #!/usr/bin/env bash or #!/bin/bashand not #!/bin/sh.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like