Skip to content

Instantly share code, notes, and snippets.

@hidsh
Last active May 22, 2025 04:11
Show Gist options
  • Save hidsh/4bc2e5b556552ebdfa12842244cb345e to your computer and use it in GitHub Desktop.
Save hidsh/4bc2e5b556552ebdfa12842244cb345e to your computer and use it in GitHub Desktop.
shellscript (zsh): Infinite wait for the success-status of given `command` for polling something
#!/usr/bin/zsh
help='Usage: waitfor interval command [args ...]
Infinite wait for the success-status (0) of given `command` for polling something.
arguments
interval: 0.0 .. 99 [sec]
command: command for polling something
args: if you need'
[ "$1" = '--help' ] && echo $help && exit 0
[ $# -lt 2 ] && echo $help && exit 1
re='^[0-9]+([.]+[0-9]+)?$'
[[ ! $1 =~ $re ]] && echo "Error: invalid interval[sec]: $1" && exit 1
sec=$1
shift
cmd=$1
! which $cmd > /dev/null && echo "Error: Command not found: $cmd" && exit 1
shift
args=$*
while true; do
echo -n .
$cmd $args > /dev/null 2>&1 && exit 0
sleep $sec
done
exit 1
$ cd ~/Downloads
$ ls foo # `foo` does *not* exist
ls: cannot access 'foo': No such file or directory
$ waitfor 1 ls foo
....
#### begin: another shell
$ touch ~/Downloads/foo
#### end: another shell
........%
$ echo $?
0 # returns 0 (success code)
#
# perhaps, need timeout? use `timeout` command like below:
#
$ timeout 10 waitfor 1 ls foo # timeout = 10 sec
@hidsh
Copy link
Author

hidsh commented May 22, 2025

this script should not be used because it fails when using with pipe.
e.g.: waitfor 1 mount | grep sdb

all i want does already exist, until built-in word.

until mount | grep -q sdb; do sleep 0.1; done

no help on zsh. but as far as i can tell from looking at man zshmisc, it seems to be a cousin of while...sucks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment