I'm losing my mind over this! I need to run a bunch of commands in parallel with a timeout, but I'm running into issues with different ways of executing a function in my script. I've tried several variations, but here's what I've got:
When I use the command `timeout 2 bash -c ". ${BASH_SOURCE}; function_inside_this_file "$count""`, it doesn't produce any output, even though everything seems to be set up correctly. On the other hand, using `timeout 2 bash -i -c ". ${BASH_SOURCE}; function_inside_this_file "$count""` gives me the expected result to the console. However, when I try to run this version in the background (adding `&`), the process just hangs indefinitely, and my script doesn't finish executing.
It's so frustrating because this command works fine: `timeout 2 bash -i -c ". ${BASH_SOURCE}; function_inside_this_file "$count"; exit;"`, but it's slow! The combination of `timeout` and `&` just doesn't work for me. I don't get what's causing the issue here with the `&` operator and why it leads to a stall. There has to be a way to run a function from a script file with a timeout in the background, right?
4 Answers
Hey, I get your frustration! You might want to try exporting the function before calling it in the background. Like this: `export -f function_inside_this_file; timeout 2 bash -c function_inside_this_file &`. This way, the function will be accessible in the subshell when you run it. I've found that helps with similar issues. Just double-check if there are any side effects being missed too!
I think you could try writing your command like this:
```bash
#! /usr/bin/env bash
function quote() {
printf -- '%qn' "$1"
}
timeout 2 bash -c "source \$(quote "${BASH_SOURCE[0]}"); function_inside_this_file \$(quote "$count")"
```
This way, it handles any special characters in your script path. Give it a shot and let me know if it helps!
It looks like your use of quotation marks may be causing issues. You might want to expand the `$count` variable inside the quotes instead of outside. Why not try restructuring it? Also, can you clarify what `$count` contains? If it's crucial for the function's execution, it could explain a lot.
Right! `$count` just holds some numeric strings that represent the target machine IDs. The function needs those to work correctly, and the command runs just fine without the `&`. It's getting tricky to manage everything in parallel!
Also, just a heads up, you shouldn't assign a value to `BASH_SOURCE`. It could create confusion since that's a special variable in bash. Stick with lowercase variable names to avoid overriding shell variables. Just a little tip!
Thanks for the reminder! I never tried to assign it, just using it to source the script. It's just odd how the different versions give mixed results.
Tried that before, but it didn't work. Without the `-i` flag, the function just won't run when `timeout` is involved. It seems to hang at the function call itself.