Bash one-liners: Condition-based variables

Posted on ‐ Tagged bash

Here’s a useful way to set variables based on a condition using bash:

    [[ $(/bin/ls /etc/init/celery.conf 2> /dev/null ) ]] && CELERY=YES || CELERY=NO 

In this case I’m simply checking to see if an upstart configuration file exists, but you can replace with any condition. I like this method better than a multi-line if statement like so:

    if [ -f /etc/init/celery.conf ]; then
        CELERY=YES
    else
        CELERY=NO
    fi 

That just looks ugly to me and takes up too much space.

comments powered by Disqus