Nam Ngo
Nam Ngo

Reputation: 2163

Bash condition with AND OR operators

I've got a bash shell that gets options as either month (mm) and year (yyyy) or time (mmyyyy). I can parse options and assign them to variables. Now, I need some conditions to check for those variables. What I need is: if (month AND year) OR time then proceed else display usage. This is my code and it doesn't seem to be working.

if [[ -z $MONTH && -z $YEAR ]] || [[ -z $TIME ]]; then
    usage
    exit 1
else
    if [[ -z $TIME ]]; then
        echo $MONTH$YEAR
    else
        echo $TIME
    fi
fi

Upvotes: 1

Views: 441

Answers (1)

ruakh
ruakh

Reputation: 183280

Your logic is a bit backward. This:

if [[ -z $MONTH && -z $YEAR ]] || [[ -z $TIME ]]; then
    usage

("if I'm missing both month and year, it's an error; or, if I have those, but am missing time, it's an error") should be this:

if [[ -z $MONTH || -z $YEAR ]] && [[ -z $TIME ]]; then
    usage

("if I'm missing month or year, and I'm missing time, it's an error").

Upvotes: 5

Related Questions