POSIX sh 检查(测试)内置设置选项的值

POSIX sh check (test) value of builtin set option

在 POSIX sh 中,您可以使用 set:

设置选项
#!/bin/sh

set -u;

echo "$notset";

给出预期:

parameter not set or null

但是如何检查选项 -e 是否已设置?

我想在我的脚本的某个时刻将其关闭,但仅当它之前处于打开状态时才将其设置回打开状态。

shell 选项作为单个字符的字符串保存在 $- 中。您用

测试 -e
case $- in
(*e*)    printf 'set -e is in effect\n';;
(*)      printf 'set -e is not in effect\n';;
esac

根据接受的答案,我这样做了:

存储选项状态(空字符串=关闭,选项字符=打开)

option="e"
option_set="$(echo $- | grep "$option")"

将其恢复为之前存储在 option_set 中的值,以防我修改其状态:

if [ -n "$option_set" ]; then 
    set -"$option"
else 
    set +"$option" 
fi

如果您想使用该解决方案,这里有一个测试脚本:

#!/bin/sh

return_non_zero() {
    echo "returing non zero"
    return 1
}

set -e # turn on option
# set +e # turn off option

echo "1. options that are set: $-"

option="e"
option_set="$(echo $- | grep "$option")"

echo "turn off "$option" option" && set +"$option"
# echo "turn on "$option" option" && set -"$option"

echo "2. options that are set: $-"

# should terminate script if option e is set
return_non_zero

# restore option to prev value
if [ -n "$option_set" ]; then 
    set -"$option"
else 
    set +"$option" 
fi

echo "3. options that are set: $-"

echo "END"