Shell 脚本“||” {}”可读的替代方案
当我遇到包含此代码的 这个答案 时,我正在寻找一种方法来检查是否使用 Shell 脚本安装了程序:
hash foo 2>&- || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
但是该代码不太(人类)可读,该语法的替代方案是什么?
I was looking for a way to check if a program is installed using Shell Script when I came across this answer which contained this code:
hash foo 2>&- || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
But that code isn't very (human) readable, what is the alternative for that syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可读性是非常主观的。我特别认为,一旦您知道
||
表示短路 OR ,原文就非常具有可读性。因此,您将原文读作“执行此操作,OR 如果该操作失败,则执行此操作”。不使用
||
的等效代码是:Readability is very subjective. I particularly think the original is very readable, once you know that
||
means a short-circuiting OR. So you read the original as "do this, OR this if that one fails".The equivalent code without using
||
is:对于任何习惯 shell 脚本的人来说这是完全可读的,因为它是一个习惯用法。可读性的唯一障碍是缺乏换行符:
that's perfectly readable for anyone accustomed to shell scripts, because it's an idiom. the only hindrance to readability is the lack of newlines: