#trap ... EXIT 在 shell 结束时运行,无论以何种方式结束;
#用 ( ) 而不是 { } 定义的函数在子 shell 中运行,
#带有自己的 trap,类似 try ... finally
throwIfTrue() (
trap 'echo "finally"' EXIT
if [[ $1 == true ]]; then
echo "except"
exit 1
fi
)
throwIfTrue true
#输出 "except" 和 "finally"
throwIfTrue false
#只输出 "finally"
#trap 的常见用途是清理:即使子 shell 因错误结束,
#文件也会被删除
(
trap 'rm -f temp.txt' EXIT
echo "data" > temp.txt
exit 1
)
[[ -e temp.txt ]] && fileLeft=true || fileLeft=false
#fileLeft is false
echo "fileLeft is $fileLeft"