Fish shell: how to wait for a background job and get its exit status?

Viewed 186

I'm trying to figure out how to run multiple long-running commands in parallel in the fish shell, but with proper error handling so that my overall script/one-liner doesn't succeed unless they all do. But I can't figure out how to deal with exit status.

The posix spec for wait says that it should communicate exit status:

The exit status returned by the wait utility shall be the exit status of the process requested by the last pid operand.

And the GitHub thread about adding wait to fish spends a lot of time discussing exit statuses (but then was closed suddenly years later without explanation). But it doesn't seem that wait actually does deal correctly with exit statuses in fish:

> ls nonexistent; echo $status
ls: cannot access 'nonexistent': No such file or directory
2

> ls nonexistent &; wait $last_pid; echo $status
ls: cannot access 'nonexistent': No such file or directory
0
fish: Job 1, 'ls nonexistent &' has ended

How can I wait for a background job to terminate and be able to tell whether it succeeded or not?

1 Answers

wait does not yet expose the exit status, but you can get it with an on-process-exit event handler:

sleep 3 &
function sleep_ended --on-process-exit $last_pid
    echo "pid $argv[2] exited with status $argv[3]"
end
wait
Related