linux – 函数内部的错误处理,以便我们可以退出脚本
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了linux – 函数内部的错误处理,以便我们可以退出脚本,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2771字,纯文字阅读大概需要4分钟。
内容图文
![linux – 函数内部的错误处理,以便我们可以退出脚本](/upload/InfoBanner/zyjiaocheng/965/512dbbed5b2646cba559dfdf78f06331.jpg)
我有两个这样的映射文件,如下所示:
primary_mapping.txt
{1=[343, 0, 686, 1372, 882, 196], 2=[687, 1, 1373, 883, 197, 736, 1030, 1569], 3=[1374, 2, 884, 737, 198, 1570], 4=[1375, 1032, 1424, 3, 885, 1228], 5=[1033, 1425, 4, 200, 886]}
secondary_mapping.txt
{1=[1152, 816, 1488, 336, 1008], 2=[1153, 0, 817, 337, 1489, 1009, 1297], 3=[1, 1154, 1490, 338], 4=[1155, 2, 339, 1491, 819, 1299, 1635], 5=[820, 1492, 340, 3, 1156]}
在上面的映射文件中,每个clientId都有主映射和辅助映射.例如:clientId 1具有343,0,686,1372,882,196主映射和1152,816,1488,336,1008辅助映射.同样对于其他clientIds也是如此.
下面是我的shell脚本,它在其中打印特定clientid的主映射和辅助映射:
#!/bin/bash
mapfiles=(primary-mappings.txt secondary-mappings.txt)
declare -a arr
mappingsByClientID () {
id=$1 # 1 to 5
file=${mapfiles[$2]} # 0 to 1
arr=($(sed -r "s/.*\b${id}=\[([^]\]+).*/\1/; s/,/ /g" $file))
echo "${arr[@]}"
}
# assign output of function to an array
# this prints mappings for clientid 3. In general I will take this parameter from command line.
pri=($(mappingsByClientID 3 0))
snd=($(mappingsByClientID 3 1))
现在让我们说如果我们找不到特定clientid的主映射或辅助映射,那么我想通过记录消息退出具有非零状态代码的shell脚本.我尝试退出子shell,它对我没用.这可能吗?
解决方法:
你可以做到这一点(纳入了我们的大师Charles Duffy的所有伟大建议):
mappingsByClientID () {
(($# != 3)) && { echo "Insufficient arguments" >&2; exit 1; }
declare -n arr=$1 # for indirect assignment (need **Bash 4.3 or above**)
id=$2 # 1 to 5
file=${mapfiles[$3]} # 0 to 1
[[ $file ]] || { echo "No mapping file found for id '$id', type '$2'" >&2; exit 1; }
[[ -f $file ]] || { echo "File '$file' does not exist" >&2; exit 1; }
# Note: the word boundary `\b` is not supported in ERE
# See post: https://stackoverflow.com/q/27476347/6862601
if ! grep -q "[{ ]$id=" "$file"; then
echo "Couldn't find mapping for id '$id' in file '$file'" >&2
exit 1
fi
mapfile -t arr < <(sed -r "s/.*[{ ]$id=\[([^]\]+).*/\1/" "$file" | tr -s '[ ,]' '\n')
if ((${#arr[@]} == 0)); then
echo "Couldn't find mapping for id '$id' in file '$file'" >&2
exit 1
fi
echo "${arr[@]}"
}
现在调用没有子shell $()的函数,以便函数内的退出实际上将退出脚本:
mappingsByClientID pri 3 0
mappingsByClientID sec 3 1
在函数中执行错误检查是一种更好的做法.
如果您不希望函数退出,可以在调用函数后检查调用者代码中的数组大小.
如果您使用的是不支持namerefs的Bash版本,则可以对数组使用全局变量,让我们说arr是全局变量,然后:
arr=() # initialize the global
mappingsByClientID 3 0
pri=("${arr[@]}") # make a copy of the global array into pri
mappingsByClientID 3 1
sec=("${arr[@]}") # make a copy of the global array into sec
相应地修改mappingsByClientID以使用全局变量而不是nameref.
有关:
> Matching word boundary with Bash regex
> Creating an array from a text file in Bash
内容总结
以上是互联网集市为您收集整理的linux – 函数内部的错误处理,以便我们可以退出脚本全部内容,希望文章能够帮你解决linux – 函数内部的错误处理,以便我们可以退出脚本所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。