首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在shell中编写try catch finally

在shell中编写try catch finally
EN

Stack Overflow用户
提问于 2013-03-27 18:21:43
回答 6查看 69.4K关注 0票数 76

有没有像java try catch finally这样的linux bash命令?还是linux shell一直在运行?

try {
   `executeCommandWhichCanFail`
   mv output
} catch {
    mv log
} finally {
    rm tmp
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-03-27 18:29:10

嗯,差不多吧:

{ # your 'try' block
    executeCommandWhichCanFail &&
    mv output
} || { # your 'catch' block
    mv log
}

 rm tmp # finally: this will always happen
票数 108
EN

Stack Overflow用户

发布于 2013-11-20 09:32:16

根据您的示例,无论脚本如何退出,您似乎都在尝试执行类似于始终删除临时文件的操作。要在Bash中执行此操作,请尝试trap内置命令来捕获EXIT信号。

#!/bin/bash

trap 'rm tmp' EXIT

if executeCommandWhichCanFail; then
    mv output
else
    mv log
    exit 1 #Exit with failure
fi

exit 0 #Exit with success

rm tmp语句中的trap始终在脚本退出时执行,因此将始终尝试删除文件"tmp“。

还可以重置已安装的陷阱;调用仅带信号名称的陷阱将重置信号处理程序。

trap EXIT

有关更多详细信息,请参阅bash手册页面:man bash

票数 124
EN

Stack Overflow用户

发布于 2020-03-01 02:31:24

我在我的脚本中成功地使用了以下语法:

# Try, catch, finally
(echo "try this") && (echo "and this") || echo "this is the catch statement!"

# this is the 'finally' statement
echo "finally this"

如果其中一条try语句抛出错误或以exit 1,然后解释器转到catch语句,然后转到finally语句。

如果两个try语句都成功(和/或以exit)时,解释器将跳过catch语句,然后运行finally语句。

示例_1:

goodFunction1(){
  # this function works great
  echo "success1"
}

goodFunction2(){
  # this function works great
  echo "success2"
  exit
}

(goodFunction1) && (goodFunction2) || echo "Oops, that didn't work!"

echo "Now this happens!"

输出_1

success1
success2
Now this happens!

示例_2

functionThrowsErr(){
  # this function returns an error
  ech "halp meh"
}

goodFunction2(){
  # this function works great
  echo "success2"
  exit
}

(functionThrowsErr) && (goodFunction2) || echo "Oops, that didn't work!"

echo "Now this happens!"

输出_2

main.sh: line 3: ech: command not found
Oops, that didn't work!
Now this happens!

示例_3

functionThrowsErr(){
  # this function returns an error
  echo "halp meh"
  exit 1
}

goodFunction2(){
  # this function works great
  echo "success2"
}

(functionThrowsErr) && (goodFunction2) || echo "Oops, that didn't work!"

echo "Now this happens!"

输出_3

halp meh
Oops, that didn't work!
Now this happens!

请注意,函数的顺序将影响输出。如果需要分别尝试和捕获这两个语句,请使用两个try catch语句。

(functionThrowsErr) || echo "Oops, functionThrowsErr didn't work!"
(goodFunction2) || echo "Oops, good function is bad"

echo "Now this happens!"

输出

halp meh
Oops, functionThrowsErr didn't work!
success2
Now this happens!
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15656492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档