Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling user input during an infinite loop in bash

Tags:

bash

selenium

I have this bash script which basically starts the web and selenium servers with progress indicator. Since it takes some time to selenium server to start I'm checking the status in an infinite loop.

The problem is, while waiting for it to start I press keys accidentaly it's displayed in the screen and if the loop ends (times out) it's also displayed in the command prompt too.

I want to disable all user input (except the control keys of course) while inside the loop:

start_selenium() {
    echo -n "Starting selenium server"
    java -jar ${selenium_jar} &> $selenium_log &

    # wait for selenium server to spin up! (add -v for verbose output)
    i=0
    while ! nc -z localhost 4444; do
        sleep 1
        echo -n "."
        ((i++))
        if [ $i -gt 20 ]; then
            echo
            echo -e $bg_red$bold"Selenium server connection timed out"$reset
            exit 1
        fi
    done
} 
like image 540
madpoet Avatar asked Oct 01 '14 08:10

madpoet


2 Answers

The stty invocations are from http://www.unix.com/shell-programming-and-scripting/84624-nonblocking-i-o-bash-scripts.html

This still respects Ctrl-C, but doesn't show input, and consumes it so it's not left for the shell.

#!/bin/bash

hideinput()
{
  if [ -t 0 ]; then
     stty -echo -icanon time 0 min 0
  fi
}

cleanup()
{
  if [ -t 0 ]; then
    stty sane
  fi
}

trap cleanup EXIT
trap hideinput CONT
hideinput
n=0
while test $n -lt 10
do
  read line
  sleep 1
  echo -n "."
  n=$[n+1]
done
echo
like image 59
Nick Russo Avatar answered Oct 14 '22 13:10

Nick Russo


Use stty to turn off keyboard input.

stty -echo
#### Ur Code here ####
stty echo

-echo turns off keyboard input and stty echo reenables keyboard input.

like image 26
Fazlin Avatar answered Oct 14 '22 15:10

Fazlin