Shell Script "|| {}" Readable Alternative

I was looking for a way to check if a program was installed using Shell Script when I came across this answer that contained this code:

hash foo 2>&- || { echo >&2 "I require foo but it not installed. Aborting."; exit 1; } 

But this code is not very (human) readable, what is an alternative to this syntax?

+4
source share
2 answers

Readability is very subjective. I especially think that the original is very readable if you know that || means short circuit OR . So, you read the original as "do it, OR if it fails."

Equivalent code without using || is an:

 if ! hash foo 2>&- then echo >&2 "I require foo but it not installed. Aborting." exit 1 fi 
+9
source

which reads great for those who are used to shell scripts because this is an idiom. the only obstacle to readability is the lack of new lines:

 hash foo 2>&- || { echo >&2 "I require foo but it not installed. Aborting." exit 1 } 
+2
source

Source: https://habr.com/ru/post/1389771/


All Articles