I want to exit the script if any key is pressed.
#!/bin/sh
while true; do
df -h | head
sleep 10
clear
done
Any suggestion?
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityYou'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
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:
#!/bin/bash
while true; do
{ clear; df -h | head; } </dev/null
read -n 1 -t 10 && break
done; read -t 0.1 -n 1000000
Notes:
bash
, not sh
, because of read -n
./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.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
:
#!/bin/bash
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