linux - Shell 脚本错误处理

标签 linux bash shell scripting

我正在清理脚本的输出。例如:

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 - POSIX rm使用 -f 时忽略丢失的文件。
  • 如果可以避免,不要使用 shell。 Python 和其他现代语言内置了很多复杂的错误处理。

关于linux - Shell 脚本错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27833022/

相关文章:

json - 用文件内容替换关键字

shell - 如何在 shell 中使用 awk 变量

windows - 在 VC2005/08 和 Mac Os env 中编译 LibXML2

c++ - 在 Linux 上使用 C++ 对 Active Directory 进行身份验证

bash - 获取字符串中的第一个元素

bash - 无需打开浏览器即可进行 gcloud 身份验证?

python - Python 子进程中的 Linux 命令

ruby-on-rails - #<BottleSpecification :0x00000000e9fdb8> 的未定义方法 `rebuild'

python - 顺序调用多个子进程

Bash 脚本不访问路径中包含空格的文件