Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script "|| { }" Readable Alternative

Tags:

syntax

bash

shell

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?

like image 732
Nathan Campos Avatar asked Dec 21 '22 03:12

Nathan Campos


2 Answers

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:

if ! hash foo 2>&-
then
    echo >&2 "I require foo but it's not installed.  Aborting."
    exit 1
fi
like image 52
Juliano Avatar answered Dec 31 '22 12:12

Juliano


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:

hash foo 2>&- || {
  echo >&2 "I require foo but it's not installed.  Aborting."
  exit 1
}
like image 30
just somebody Avatar answered Dec 31 '22 11:12

just somebody