在 bash 中,在返回/退出函数之前 popd
的正确方法是什么?例如,
function fn () {
pushd ~ >/dev/null
if [ $1 = $2 ]; then
return 0;
elif [ $2 = $3 ]; then
return 1;
else
return 2;
fi
popd >/dev/null
}
我应该在每次返回之前写 popd
吗?或者,我应该换一种方式吗?
最佳答案
为此我可能会这样做:
fn() {
pushd ~ >/dev/null
if [ "$1" = "$2" ]; then
ret=0
elif [ "$2" = "$3" ]; then
ret=1
else
ret=2
fi
popd >/dev/null
return $ret
}
这样我就不必在每次返回之前重复“清理”代码。
另一种方法是在子 shell 中完成工作,并将 cd
到所需的目录,尽管该子 shell 无法修改父环境(毕竟这是我们想要的一部分) .
fn() (
cd ~
if [ "$1" = "$2" ]; then
return 0
elif [ "$2" = "$3" ]; then
return 1
else
return 2
fi
)
关于bash - 在返回/退出函数之前弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40473846/