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/bash and not #!/bin/sh.

1

Your Answer

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

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest