Skip to content

Instantly share code, notes, and snippets.

@cwacek
Last active January 11, 2020 22:53
Show Gist options
  • Save cwacek/6798275 to your computer and use it in GitHub Desktop.
Save cwacek/6798275 to your computer and use it in GitHub Desktop.
Run a command with a timeout. This is useful for things like 'df' which can hang if NFS is misbehaving
#!/bin/bash
timeout=$1
shift
cmd=$1
shift
args=$@
if [[ -z "$cmd" ]]; then
echo "timeout.sh <seconds> <cmd>"
exit 1
fi
if [[ -z "$timeout" ]]; then
echo "timeout.sh <seconds> <cmd>"
exit 1
fi
count=0
stdbuf -oL -eL $cmd $args > $cmd.out &
PID=$!
while kill -0 $PID && [ $count -lt $timeout ]
do
sleep 1
count=$(expr $count + 1)
done
kill -9 $PID >/dev/null 2>&1
cat ${cmd}.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment