Make shopt change local to function

前端 未结 4 1889
渐次进展
渐次进展 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条回答
  •  猫巷女王i
    2021-01-01 10:40

    You can use an associative array to remember the previous setting and then use it for reverting to the earlier setting, like this:

    shopt_set

    declare -gA _shopt_restore
    shopt_set() {
        local opt count
        for opt; do
            if ! shopt -q "$opt"; then
                echo "$opt not set, setting it"
                shopt -s "$opt"
                _shopt_restore[$opt]=1
                ((count++))
            else
                echo "$opt set already"
            fi
        done
    }
    

    shopt_unset

    shopt_unset() {
        local opt restore_type
        for opt; do
            restore_type=${_shopt_restore[$opt]}
            if shopt -q "$opt"; then
                echo "$opt set, unsetting it"
                shopt -u "$opt"
                _shopt_restore[$opt]=2
            else
                echo "$opt unset already"
            fi
            if [[ $restore_type == 1 ]]; then
                unset _shopt_restore[$opt]
            fi
        done
    }
    

    shopt_restore

    shopt_restore() {
        local opt opts restore_type
        if (($# > 0)); then
            opts=("$@")
        else
            opts=("${!_shopt_restore[@]}")
        fi
        for opt in "${opts[@]}"; do
            restore_type=${_shopt_restore[$opt]}
            case $restore_type in
            1)
                echo "unsetting $opt"
                shopt -u "$opt"
                unset _shopt_restore[$opt]
                ;;
            2)
                echo "setting $opt"
                shopt -s "$opt"
                unset _shopt_restore[$opt]
                ;;
            *)
                echo "$opt wasn't changed earlier"
                ;;
            esac
        done
    }
    

    Then use these functions as:

    ... some logic ...
    shopt_set nullglob globstar      # set one or more shopt options
    ... logic that depends on the above shopt settings
    shopt_restore nullglob globstar  # we are done, revert back to earlier setting
    

    or

    ... some logic ...
    shopt_set nullglob
    ... some more logic ...
    shopt_set globstar
    ... some more logic involving shopt_set and shopt_unset ...
    shopt_restore             # restore everything
    

    Complete source code here: https://github.com/codeforester/base/blob/master/lib/shopt.sh

提交回复
热议问题