Skip to content

Instantly share code, notes, and snippets.

@firejox
Created April 14, 2024 10:20
Show Gist options
  • Save firejox/281b50b2e2d4d72a7c0603bf0fb357b3 to your computer and use it in GitHub Desktop.
Save firejox/281b50b2e2d4d72a7c0603bf0fb357b3 to your computer and use it in GitHub Desktop.
Alternative sleep implementation
#!/bin/sh
Help()
{
cat <<-EOF
Usage: $0 NUMBER[SUFFIX]...
or: $0 OPTION
Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default),
'm' for minutes, 'h' for hours or 'd' for days. NUMBER need not be an
integer. Given two or more arguments, pause for the amount of time
specified by the sum of their values.
--help display this help and exit
EOF
}
if [ $# -eq 0 ]; then
echo "$0: missing operand"
echo "Try 'sleep --help' for more information"
exit 1
fi
ARGS=`getopt -o h --long help -n "$0" -- "$@"`
if [ $? != 0 ]; then
echo "Terminating..."
exit 1
fi
eval set -- "${ARGS}"
while true
do
case "$1" in
-h|--help)
Help
exit 0
;;
--)
shift
break
;;
*)
echo "Internal Error!"
exit 1
;;
esac
done
sleep_time=`echo "$@"|awk '
{
sum = 0;
flag = 0;
for (i = 1; i <= NF; i++) {
switch($i) {
case /inf/:
case /infinty/:
flag = 1;
exit;
case /.*d/:
sum += $i * 86400;
break;
case /.*h/:
sum += $i * 3600;
break;
case /.*m/:
sum += $i * 60;
break;
default:
sum += $i;
break;
}
}
} END {
if (flag) {
print "infinty"
} else {
print sum
}
}'`
if [ "$sleep_time" != "infinty" ]; then
exec flock -sF "$0" flock -w $sleep_time -E 0 -eF "$0" true
else
exec flock -sF "$0" flock -eF "$0" true
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment