Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Chaining OR and AND in Bash

I would like to chain the OR and AND commands so that I print the contents of a directory to stdout if the directory exists, or in the case that it does not, print a message to stdout saying that the directory "$MY_DIR" is being created and then create it.

I have the following code.

ls "$MY_DIR" || echo "Creating $MY_DIR" && mkdir -p "$MY_DIR"

Is this the correct and canonical way to do this? Will mkdir always run since echo will return 0 return status, even in the case that ls does return?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The most relevant question I have located so far is this one which does not eliminate my doubts.

>Solution :

I would not do what you are doing that way in any case. You should group your commands for clarity if for no other reason.

ls "$MY_DIR" || {
    echo "Creating $MY_DIR"
    mkdir -p "$MY_DIR"
}

This has several advantages: your intent is more clearly expressed, there is less ambiguity between what the human thinks will happen and what the computer will do, and it stops relying on the exit code from echo that you were not really interested in to begin with. Even if your original version worked entirely correctly it was more vulnerable to later, naïve modification.

A oneliner form is of course possible, if less readable:

ls "$MY_DIR" || { echo "Creating $MY_DIR"; mkdir -p "$MY_DIR"; }

As for your original method, consider this:

If the ls command fails:

false || true && echo mkdir # prints mkdir

But if the ls command succeeds

true || true && echo mkdir # also prints mkdir

Whereas

true || { true; echo mkdir; } # does not print
false || { true; echo mkdir; } # prints mkdir

It gets worse: I am not entirely clear whether ls will set an unsuccessful return code if the file/directory does not exist. It’s certainly true that GNU ls does this, and it may be common, but the standard doesn’t seem to say what constitutes success or failure, so implementations may well disagree.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading