help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to set $?


From: David
Subject: Re: How to set $?
Date: Sun, 26 Dec 2021 09:37:33 +1100

On Sun, 26 Dec 2021 at 07:35, Jeffrey Walton <noloader@gmail.com> wrote:

> I have a script that executes two sets of commands. If the first set
> fails, I want to return the error code of the first set. For example:
>
>     apt-get update && apt-get upgrade -y && apt-get dist-upgrade -y
>     saved_result="$?"
>     apt-get autoremove --purge -y && apt-get autoclean -y
>     $?="$saved_result"
>
> How do I set $?

Like this:

apt-get update && apt-get upgrade -y && apt-get dist-upgrade -y
saved_result=$?
apt-get autoremove --purge -y && apt-get autoclean -y
exit $?

Both 'exit' and 'return' commands can take a numeric argument N,
which can be used to achieve what you want.
See:

$ help exit
exit: exit [n]
    Exit the shell.

    Exits the shell with a status of N.  If N is omitted, the exit status
    is that of the last command executed.

$ help return
return: return [n]
    Return from a shell function.

    Causes a function or sourced script to exit with the return value
    specified by N.  If N is omitted, the return status is that of the
    last command executed within the function or script.

    Exit Status:
    Returns N, or failure if the shell is not executing a function or script.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]