Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash which OR operator to use - pipe v double pipe

Tags:

bash

When I'm looking at bash script code, I sometimes see | and sometimes see ||, but I don't know which is preferable.

I'm trying to do something like ..

set -e;

ret=0 && { which ansible || ret=$?; }

if [[ ${ret} -ne 0 ]]; then
    # install ansible here
fi

Please advise which OR operator is preferred in this scenario.

like image 850
danday74 Avatar asked Jan 13 '17 00:01

danday74


1 Answers

| isn't an OR operator at all. You could use ||, though:

which ansible || {
  true # put your code to install ansible here
}

This is equivalent to an if:

if ! which ansible; then
  true # put your code to install ansible here
fi

By the way -- consider making a habit of using type (a shell builtin) rather than which (an external command). type is both faster and has a better understanding of shell behavior: If you have an ansible command that's provided by, say, a shell function invoking the real command, which won't know that it's there, but type will correctly detect it as available.

like image 133
Charles Duffy Avatar answered Nov 15 '22 20:11

Charles Duffy