I’m doing a bash script to check cryptocurrency prices, and it updates in a while loop like this:
Crypto prices real time updating
The problem is that due to being an infinite loop, I couldnt think of a way of returning to the main menu, but today seeing timeout command I’ve tried doing this so that I can return to the main menu if there’s a key pressed:
echo -e "nnt${blue} Press a key to return to the Main Menu..${end}"; timeout 1 bash -c "read -s -n 1 key" if [ $(echo $?) -eq "0" ]; then mainMenu fi
In linux command line it is working (if a key is pressed before the timeout, status code equals 0, else, status code equals 124) but for some reason using this structure into the while loop doesnt work.
Advertisement
Answer
You’re using too much of bash 😛 read
itself also has a timeout option -t
. The line below says “if read doesn’t exit correctly, do not show content DATA
. If you do not react within one second, the exit status will be 142
.
read -t 1 -p "Enter something: " DATA [[ $? -ne 0 ]] || echo $DATA
You can translate this to:
read -t 1 -p "Enter something: " DATA [[ $? -ne 0 ]] || mainMenu
If you want to exit the while loop entirely, use break
instead.
ps. small note on the if statement:
if [[ $? -eq 0 ]]; then mainMenu fi