I want to exit the script if any key is pressed.

while true; do
   df -h | head
   sleep 10

Any suggestion?

3 Answers 3


You'd better use watch command:

watch -n10 'df -h | head'

Use Ctrl+c to stop the command.

The watch man page says:

watch - execute a program periodically, showing output fullscreen

  • You can Ctrl+C the original script. The point is to use any key. Jun 28, 2018 at 11:53

Replace sleep 10; with read -t 10 -n 1 exitwhile; if [ -n "$exitwhile" ]; then break; fi

read -t 10 -n 1 exitwhile waits 10sec for input without confirmation with enter and puts input into variable exitwhile. if that variable is not empty the while-loop will break.

…has to be modified though, because it will only break on character keys


This will exit on almost any key:

while true; do
   { clear; df -h | head; } </dev/null
   read -n 1 -t 10 && break
done; read -t 0.1 -n 1000000


  • The shebang calls bash, not sh, because of read -n.
  • The redirection from /dev/null is to prevent commands other than read from exhausting the stdin (clear and df may not do this, but in general commands may). This way any input goes to read eventually.
  • The final read is to discard excessive characters from stdin. Some keys generate more than one character (research "escape sequences"); it's also possible to hit multiple keys while df (or any other command you wish to use) is running. Without the final read these extra characters would litter your command line.

Alternative approach, with watch:

watch -n 10 df -h &   # put to the background
read -n 1
kill $!               # kill the the job most recently placed into the background
read -t 0.1 -n 1000000

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.