7

I would like to know if these 2 ways are equivalent:

First:

#!/bin/bash
if [ -x $FILE ]
then
  echo "You have execution permission to a "$FILE""
else
  echo "You don't have execution permission to a "$FILE""
fi

Second:

#!/bin/bash
[ -x $FILE ] && echo "You have execution permission to a "$FILE"" || echo "You don't have execution permission to a "$FILE""
  • 1
    Your quoting is wrong: [ -x "$FILE" ]; echo "You have execution permission to '$FILE'" – Hauke Laging May 21 '14 at 23:42
  • Ok thanks, but seems my code is working the same way(maybe inconsistent with standard :)) But are these 2 ways equivalent? – user3014282 May 21 '14 at 23:45
  • 1
    Whether your version works depends on it whether the file name contains whitespace (or, more precise: IFS characters). – Hauke Laging May 21 '14 at 23:47
5

The structures are not equivalent in general but in this case they are. The reason is that echo always has exit code 0. If that was a command instead which can exit with a code greater than zero then "the other branch" would be executed, too. This is impossible in the if case.

  • 2
    The if case is also much more readable. – jkt123 May 21 '14 at 23:46
  • 1
    @user3014282: To elaborate Hauke's answer, [ -e /tmp ] && { echo 1 ; false ; } || echo 2 will print both 1 and 2. Recasting the same using if ... then ... else ... fi will print only 1. So && || is not an exact equivalent of the other. – jamadagni Oct 25 '14 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.