是否有一个猛砸尝试捕捉命令 [英] Is there a TRY CATCH command in Bash

查看:107
本文介绍了是否有一个猛砸尝试捕捉命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个shell脚本,需要检查终端的应用程序已安装。我想用一个try / catch命令要做到这一点,除非有更合适的方法。


解决方案

  

是否有一个猛砸尝试捕捉命令?


没有。

击不具备所有奢侈,你可以在很多编程语言中找到,也这是真的,庆典没有比其他编程语言豪宅少。

有是不是一个真正的的try / catch 在bash,但你可以使用实现了相当类似的行为&放大器;&安培; ||

使用 ||

如果命令1 失败,那么你会遇到命令2 如下:

 命令1 ||命令2

使用

相似&放大器;&安培; 您可以运行命令2 如果命令1 成功

现在,如果你想的确切风味的try / catch 那就试试吧。

  {#这是我的bash try块    命令1&放大器;&安培;
    #save你的输出} || {#这就是catch块
    #保存日志异常
}

另外庆典包含一些错误处理机制也

 设置-e

如果一个简单的命令失败,它会立即停止你的脚本。我想,这应该是默认的行为:既然这样的错误几乎总是意味着意想不到的事情,它是不是真的'理智',以保持执行以下命令

和也,为什么不 IF ... ELSE 。这是你最好的朋友。

I'm writing a Shell script and need to check that a terminal app has been installed. I want to use a TRY/CATCH command to do this unless there is a neater way.

解决方案

Is there a TRY CATCH command in Bash?

No.

Bash doesn't have all luxury as you can find in many programming language and also it's true that bash doesn't have less luxury than other programming language.

There is not really a try/catch in bash but you can achieve a quite similar behavior using && or ||

Using ||

if command1 fails then you will run command2 as follows

command1 || command2

similar using && you can run command2 if command1 successful

Now if you want exact flavor of try/catch then try it

{ # this is my bash try block

    command1 &&
    #save your output

} || { # this is catch block
    # save log for exception 
}

Also bash contain some error handling mechanism also

set -e

It will immediately stop your script if a simple command fails. I think this should have been the default behavior: Since such errors almost always signify something unexpected, it is not really 'sane' to keep executing the following commands.

And also why not if...else. It is your best friend.

这篇关于是否有一个猛砸尝试捕捉命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆