Make shopt change local to function

前端 未结 4 1880
渐次进展
渐次进展 2021-01-01 10:03

I\'m trying to write a bash function that uses nocasematch without changing the callers setting of the option. The function definition is:

is_he         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-01 10:40

    Use a RETURN trap

    Commands specified with an RETURN trap are executed before execution resumes after a shell function ... returns...

    The -p option [to shopt] causes output to be displayed in a form that may be reused as input.

    – https://www.gnu.org/software/bash/manual/bash.html

    foobar() {
        trap "$(shopt -p extglob)" RETURN
        shopt -s extglob
    
        # ... your stuff here ...
    
    }
    

    For test

    foobar() {
        trap "$(shopt -p extglob)" RETURN
        shopt -s extglob
    
        echo "inside foobar"
        shopt extglob # Display current setting for errexit option
    }
    
    main() {
        echo "inside main"
        shopt extglob # Display current setting for errexit option
        foobar
        echo "back inside main"
        shopt extglob # Display current setting for errexit option
    }
    

    Test

    $ main
    inside main
    extglob         off
    inside foobar
    extglob         on
    back inside main
    extglob         off
    

    Variation: To reset all shopt options, change the trap statement to:

    trap "$(shopt -p)" RETURN
    

    Variation: To reset all set options, change the trap statement to:

    trap "$(set +o)" RETURN
    

    Note: Starting with Bash 4.4, there's a better way: make $- local.

    Variation: To reset all set and all shopt options, change the trap statement to:

    trap "$(set +o)$(shopt -p)" RETURN
    

    NOTE: set +o is equivalent to shopt -p -o:

    +o Write the current option settings to standard output in a format that is suitable for reinput to the shell as commands that achieve the same options settings.

    – Open Group Base Specifications Issue 7, 2018 edition > set

提交回复
热议问题