Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm generally not a huge fan of inlining the command or cluttering up my local directory with little scripts to get around the fact that it must be a subprocess you can send a signal to. I use a wrapper like this, which exports a function containing whatever complex logic I want to time out. The funky quoting in the timeout bash -c argument is a generalized version of what aidenn0 mentioned in another comment here (passing in args safely to subproc).

    #!/usr/bin/env bash

    long_fn () { # this can contain anything, like OPs until curl loop
      sleep $1
    }

    # to TIMEOUT_DURATION BASH_FN_NAME BASH_FN_ARGS...
    to () {
      local duration="$1"; shift
      local fn_name="$1"; shift
      export -f "$fn_name"
      timeout "$duration" bash -c "$fn_name"'  "$@"' _ $@
    }

    time to 1s long_fn 5 # will report it ran 1 second


You need `"$@"`, not just `$@` at the end of the command. Otherwise it will split any arguments that have spaces in them. E.g. try

    long_fn() {
      echo "$1"
      sleep "$2"
    }

    to 1s long_fn "This has spaces in it" 5


My bad on that typo. I write "$@" so often in shell scripts that I should know better. Also would've been caught by shellcheck. Outside the hn edit window though, so my mistake is permanent :(




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: