0

Goal: To run a command independent of the terminal and return immediately. And if the command fails run an alternative commands independent of the terminal and return immediately.

I did the following. It works if the command works, but returns the error code as 0 even if it fails. The code can be rectified by removing the first disown but then the command doesn't returns immediately.

        ErrorCode=$(
            nohup "${Command[@]}" >/dev/null 2>&1 &
            Pid=$!
            disown "${Pid}"
            wait "${Pid}"
            echo "$?"
        )
        if ((ErrorCode != 0)); then
            nohup "${CommandAlternative[@]}" >/dev/null 2>&1 &
        else
            echo "#Debug: ErrorCode: ${ErrorCode}"
        fi

So basically I am not able to capture the error code of the previous command with disown. Command is mpv "${MusicFile}"

1
  • Have you try with canonical if? if [ "$ErrorCode" -ne 0 ] .... Commented Dec 4, 2022 at 13:52

1 Answer 1

1

Assuming that if the command fails and exits, it would be less than 3 seconds:

    "${Command[@]}" >/dev/null 2>&1 &
    Pid=$!
    disown "${Pid}"
    sleep 3
    if ! ps --pid "$Pid" >/dev/null; then
        "${CommandAlternative[@]}" >/dev/null 2>&1 &
        disown
    fi

What it does: Runs the alternative command if the previous command failed and exited in 3 seconds.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .