Martin Cracauer via plug on 3 Feb 2022 13:48:14 -0800


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

Re: [PLUG] Returning a status without leaving an environment variable hanging around


K.S. Bhaskar via plug wrote on Thu, Feb 03, 2022 at 04:08:06PM -0500: 
> I have a file to be sourced by a shell (typically bash, but it needs work
> with POSIX shells). If the sourcing succeeds, it sets up an environment and
> assigns values to environment variables, but if it fails, it leaves the
> environment variables unchanged (unsets all environment variables it uses).
> 
> The high level structure in question is
> 
> if <condition> ; then
>   if <run program> ; then
>     clean up a temporary directory
>   else
>     report error
>   fi
> else
>   report error
> fi
> 
> I would like to enhance it to return a status which can be queried, e.g.,
> with $?. I realize that I can use an environment variable with a name that
> is guaranteed for all practical purposes to not collide with any existing
> environment variable. I was wondering if there is any way to return a
> status without using an environment variable, e.g., if there were some way
> to return $xyz and unset xyz in one fell swoop.


You need to wrap a function

foo () {
    local err
    if <condition> ; then
        if run-program ; then
            nuke
        else
            err=$?
            return err
        fi
    else
        return 42
    fi
    return 0
}
foo

-- 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Martin Cracauer <cracauer@cons.org>   http://www.cons.org/cracauer/
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug