是否可以检查 -e 是否在 bash 脚本中设置?

ust*_*sta 10 bash shell-script

如果 shell 函数需要特定的 -e/+e 设置才能工作,是否可以在本地设置该设置,然后在退出该函数之前将其恢复到以前的设置?

myfunction()
{
   # Query here if -e is set and remember in a variable?
   # Or push the settings to then pop at the end of the function?
   set +e
   dosomething
   doanotherthing
   # Restore -e/+e as appropriate, don't just do unconditional   set -e
}
Run Code Online (Sandbox Code Playgroud)

meu*_*euh 16

您当前在变量中设置了标志$-,因此您可以在函数开始时保留它并在之后恢复它。

save=$-
...
if [[ $save =~ e ]]
then set -e
else set +e
fi
Run Code Online (Sandbox Code Playgroud)


Mar*_*iae 5

您可以通过变量 SHELLOPTS 读取标志值:

  > set +e 
  > echo $SHELLOPTS
    braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  > set -e 
  > echo $SHELLOPTS
    braceexpand:emacs:errexit:hashall:histexpand:history:interactive-comments:monitor
Run Code Online (Sandbox Code Playgroud)

您会看到,设置后,出现了中的set -e值。您可以从那里检查它。errexit$SHELLOPTS

但是,您可以通过记住以下几点来解决此问题(如果您愿意!):根据手册

-e

.....该选项分别适用于shell环境和各个子shell环境。

因此,如果您在子 shell 中执行函数,例如

   zz="$(myfunction)"
Run Code Online (Sandbox Code Playgroud)

您不必担心errexit调用环境中是否设置了该变量,您可以根据需要设置它。