如何在bash case语句中使用条件构造?

Arronical

我需要使用Bash shell检查从包装脚本中启动的两个子脚本的返回码。

如果任何一个下标都失败,它们将产生一个负整数作为返回码。如果脚本有小错误,它将产生一个正整数。我执行完全成功,返回码将为0。

我想创建一个变量,使其具有基于结果的另一个变量的内容。目前,我使用的是一个丑陋的大型if elif结构,但感觉应该使用一条case语句。

这是我当前的代码:

if [[ "$sumcreate_retval" -lt "0" ]] && [[ "$movesum_retval" -lt "0" ]]
then
   script_retcode="$both_warn_err"
elif [[ "$sumcreate_retval" -gt "0" ]] && [[ "$movesum_retval" -gt "0" ]]
then
   script_retcode="$both_crit_err"
elif [[ "$sumcreate_retval" -gt "0" ]] && [[ "$movesum_retval" -lt "0" ]]
then
   script_retcode="$createwarn_movecrit_err"
elif [[ "$sumcreate_retval" -gt "0" ]] && [[ "$movesum_retval" -eq "0" ]]
then
   script_retcode="$createwarn_err"
elif [[ "$sumcreate_retval" -lt "0" ]] && [[ "$movesum_retval" -gt "0" ]]
then
   script_retcode="$createcrit_movewarn_err"
elif [[ "$sumcreate_retval" -lt "0" ]] && [[ "$movesum_retval" -eq "0" ]]
then
   script_retcode="$createcrit_err"
elif [[ "$sumcreate_retval" -eq "0" ]] && [[ "$movesum_retval" -gt "0" ]]
then
   script_retcode="$movewarn_err"
elif [[ "$sumcreate_retval" -eq "0" ]] && [[ "$movesum_retval" -lt "0" ]]
then
   script_retcode="$movecrit_err"
else
   script_retcode="$success_return"
fi

我应该如何重组呢?

注意:如果此问题更适合其他SE网站,请告诉我。

异教徒

这样的事情应该可以解决问题。我认为这样看起来不错:

case $((
  sumcreate_retval <  0 && movesum_retval <  0 ? 1 :
  sumcreate_retval >  0 && movesum_retval >  0 ? 2 :
  sumcreate_retval >  0 && movesum_retval <  0 ? 3 :
  sumcreate_retval >  0 && movesum_retval == 0 ? 4 :
  sumcreate_retval <  0 && movesum_retval >  0 ? 5 :
  sumcreate_retval <  0 && movesum_retval == 0 ? 6 :
  sumcreate_retval == 0 && movesum_retval >  0 ? 7 :
  sumcreate_retval == 0 && movesum_retval <  0 ? 8 : 
  0
)) in
  (1) script_retcode="$both_warn_err";;
  (2) script_retcode="$both_crit_err";;
  (3) script_retcode="$createwarn_movecrit_err";;
  (4) script_retcode="$createwarn_err";;
  (5) script_retcode="$createcrit_movewarn_err";;
  (6) script_retcode="$createcrit_err";;
  (7) script_retcode="$movewarn_err";;
  (8) script_retcode="$movecrit_err";;
  (0) script_retcode="success_return";;
esac

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章