Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you ask bash for the current options?

Tags:

linux

bash

shell

I am working with a number of systems built of bash scripts and other tools. Fairly often, I consider it good practice to use the -e, -u and -o pipefail options to catch error conditions and prevent unexpected behaviour.

However, some of the third party libraries (to which I have the ability to change source) do not do this, and are not happy with altering variable tests to exist with -u.

The scripts in those are likely to be sourced not executed. So what I'd like to do is in some of these, set a more permissive set of options, and then restore the stricter ones. Since the scripts in question are used by many users, some of whom have also encountered the same problem, I'd want to put this change into the third party scripts ie:

<preserve original options>
set +e +u +o pipefail
#do stuff like
if [ -n "$_UNSET_VAR" ] ; then
  cp <some stuff> <some other stuff>
fi
<restore original options (whatever they were)>

I am looking ways to preserve and restore these originals.

like image 906
Danny Staple Avatar asked Nov 21 '12 13:11

Danny Staple


1 Answers

The special parameter $- contains a list of the options that are currently set. You can parse that to see if -e and -u are set. For pipefail, you'll have to parse the output of shopt.

If you can run your code in a subshell (you aren't trying to set global variables and the like), it may be easier to do that and not worry about resetting the original state.

(
    set +e +u +o pipefail
    if [ -n "$_UNSET_VAR" ]; then
       cp <some stuff> <some other stuff>
    fi
)
like image 84
chepner Avatar answered Sep 22 '22 05:09

chepner