user3304726
user3304726

Reputation: 259

read statement help in bash to validate any key pressed

when I use read statement in shell

read -n 1 -s -t 5 -p "Starting the script in 5 seconds. Press any key to stop!" yn

How to check if any key is pressed or not , if a key is pressed then the script must exit otherwise , the script must continue ?

Upvotes: 0

Views: 133

Answers (2)

konsolebox
konsolebox

Reputation: 75508

Simply:

read -n 1 -s -t 5 -p "Starting the script in 5 seconds. Press any key to stop!" && \
    exit 1

When a key is read, read returns 0 which would allow && to process the next statement exit 1. This would end your script.

You don't have to specify a variable as well so you wouldn't need it. read uses default variable $REPLY.

Upvotes: 0

Ilya
Ilya

Reputation: 4689

You can use loop and limit read's time by one second:

#!/bin/bash
shouldStop=0
for (( i=5; i>0; i--)); do
    printf "\rStarting script in $i seconds. Press any key to stop!"
    read -s -n 1 -t 1 key
    if [ $? -eq 0 ]
    then
        shouldStop=1
    fi
done

if [ $shouldStop==1 ]
then
    printf "do not run script"
else
    printf "run script"
fi

Upvotes: 0

Related Questions