Bash script writing is a import approach to configure the linux system. Suppose we wish to add a user if not exists, the command may seems as follow:

TARGET_USER=alice
if (! id -u $TARGET_USER > /dev/null 2>&1 ); then
    echo "creating user $TARGET_USER"
    # adduser $TARGET_USER
fi

However, it is kind of too long. In this case short-circuiting is a alternative solution.

We can write a shorter code as follow:

(! id -u $TARGET_USER > /dev/null 2>&1 ) && \
    echo "creating user $TARGET_USER"

It is not enough.

The above command is equal to this script

if (! id -u $TARGET_USER > /dev/null 2>&1 ); then
    echo "creating user $TARGET_USER"
else
    false
fi

If our bash has a parameter -e, the above command will return a non zero code, and the whole process may terminated unexpected.

To avoid this situation, we may use a || to make sure it will always return true

(! id -u $TARGET_USER > /dev/null 2>&1 ) && \
    echo "creating user $TARGET_USER" || \
    true

If the result before || returns false, the whole formula will equal to

false || true

And the final result would be true.

We can also add some description.

(! id -u $TARGET_USER > /dev/null 2>&1 ) && \
    echo "creating user $TARGET_USER" || \
    echo "user $TARGET_USER already exists"
Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

Leave a Reply

Your email address will not be published. Required fields are marked *