我正在清理脚本的输出。例如:
rm -f ./file
No such file or directory
我想为这个命令实现一些错误检查,相当于一个try/catch
语句。换句话说,如果命令失败,我想捕获错误。
最佳答案
python :
try:
os.remove('./file')
champagne_for_everybody
except:
throw_myself_in_the_river
shell :
if rm ./file
then
champagne_for_everybody
else
throw_myself_in_the_river
fi
注意事项:
- 不要使用
-f
- POSIXrm
使用-f
时忽略丢失的文件。 - 如果可以避免,不要使用 shell。 Python 和其他现代语言内置了很多复杂的错误处理。
关于linux - Shell 脚本错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27833022/