1

I have a script that needs to launch a program in order for the program to create and populate some folders. The program only needs to run briefly and then close, before the script continues.

However when the program is killed, the script does not continue. How can I do this?

printf "before"

(timeout -sHUP 3s firefox)

printf "after"

I thought I was launching the program in a subshell but i am not sure if this is the case.

myol
  • 8,857
  • 19
  • 82
  • 143
  • 1
    `timeout` returns an non-zero exit status when it kills the program that it runs. If `set -e` (or, equivalently, `set -o errexit`) is in effect when that happens, the script will stop immediately and silently. The parentheses (`(...)`) ensure that the program *is* run in a subshell. That doesn't change the effect of the `errexit` setting, and it's not clear why a subshell is being used here. – pjh Mar 08 '19 at 19:04
  • I had `set -o errexit` set indeed. Any way to ignore the timeout error specifically but keep `errexit`? – myol Mar 09 '19 at 15:13

2 Answers2

1

I solved this with a hacky work around.

set -o errexit

printf "before"

timeout -sHUP 3s firefox || true

printf "after"

The alternative cleaner method would be

set -o errexit

printf "before"

set +e
timeout -sHUP 3s firefox
set -e

printf "after"
myol
  • 8,857
  • 19
  • 82
  • 143
  • It's not a hack at all. Appending `|| :` is a common idiom to suppress the exit code of a failing command when you don't care. – John Kugelman Mar 09 '19 at 15:59
0

printf takes 2 arguments - a FORMAT string, then an ARGUMENT (i.e the text to be outputted).

When you call printf "before" you are actually passing a format string with no argument, which is not displayed properly.

The easiest fix is to instead use echo:

echo "before"
timeout -sHUP 3s firefox
echo "after"

Or if you need formatting, to instead do e.g.:

printf "%s\n" "before"
timeout -sHUP 3s firefox
printf "%s\n" "after"
match
  • 10,388
  • 3
  • 23
  • 41
  • 3
    Addendum - `printf` will work fine with one argument - he just didn't include a newline, which unlike `echo` it doesn't add by default. `printf "before\n"` – Paul Hodges Mar 08 '19 at 14:53
  • stdout was just to make the example concise for stack overflow, the program has various other method calls and bash commands that get ignored after `timeout`. The issue seems to be in the use of `set -o errexit` – myol Mar 09 '19 at 15:15