lovesunix
lovesunix

Reputation: 33

Unix test for existence or file

[ -f /tmp/myfile.txt ] && echo "File exists" || echo "No such file"

How does this work? Specifically the the evaluation of && and ||.

Upvotes: 2

Views: 2912

Answers (2)

Vorsprung
Vorsprung

Reputation: 34297

The basic idea is that it runs from left to right

first it evaluates -f /tmp/myfile.txt which is true if the file exists and is a file

next it tries to evaluate the && which takes a left and a right argument. It's a logical "and"

it does lazy evaluation from left to right so if the file test is true then it checks the echo command for true, which it does by executing it. Presumably "true" in shell world means it executes normally with a zero exit code

If either of the file test or the echo ( the two args for the && ) are false then the output from the && is false and this is passed to the right

The || is a logical "or" and also has a left and right arg. If the left arg is true then it stops there as it is lazy

If the left arg is false ( the file doesn't exist ) then the right hand arg is run

Upvotes: 0

kojiro
kojiro

Reputation: 77059

&& and || are control operators that determine whether the following command should be executed based on the exit status of the prior command. From man (1) bash:

The control operators && and || denote AND lists and OR lists, respectively. An AND list has the form

  command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

An OR list has the form

  command1 || command2

command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.

[, or test, returns a zero exit status if the command passes the test. From help test:

test: test [expr] Exits with a status of 0 (true) or 1 (false) depending on the evaluation of EXPR.

So when you do

[ -f /tmp/myfile.txt ] && echo foo || echo bar

what you're really saying is (read this carefully, please) If the file exists, echo foo. If the file does not exist or the echo foo command fails, echo bar.

This is the subtle, but critical difference between these control operators and an if…then command.

Upvotes: 5

Related Questions