30 ms·
I can't help sharing one of the loveliest uses of `kill 0` I know: #!/bin/sh # # Usage: upto LIMIT COMMAND # Run COMMAND until LIMIT
by ykonstant 2y ago
I can't help sharing one of the loveliest uses of `kill 0` I know:
#!/bin/sh
#
# Usage: upto LIMIT COMMAND
# Run COMMAND until LIMIT seconds have passed, then exit.
#
test "$1" -gt 0 || {
printf '%s\n' " Error: first argument must be a positive integer."
exit 1
}
sh -ic '
sleeptime=$1
shift
exec 3>&1 2>&3
{
"$@" >&3
kill 0
} |
{
sleep "${sleeptime}"
kill 0
}
' sh "$@"
- usr1106 2y agoNice for learning. For practical use I would prefer https://www.man7.org/linux/man-pages/man1/timeout.1.html https://www.man7.org/linux/man-pages/man1/timeout.1.html
- ykonstant 2y agoWhat are the benefits of one over the other?
- usr1106 2y agoYour script does not handle stderr, stdout, and SIGINT correctly, probably more. With enough work at least some of them could be fixed, maybe even all. But why reinventing the wheel if timeout is contained in coreutils and available on nearly every Linux machine?