Home > Uncategorized > Ternary operator in bash

Ternary operator in bash

Here’s a really quick tip for bash programmers.

In languages like C++, Java, Python, and the like, there’s the concept of a ternary operator.  Basically it allows you to assign one value if a condition is true, else another.

In C/Java:

int x = valid ? 0 : 1;

In Python:

x = 0 if valid else 1

In Scala:

val x = if (valid) 0 else 1

Well, there’s no ternary operator in Bash, but there is a way to fake it.

[ $valid ] && x=1 || x=0

Where whatever conditional you want is within the brackets.

If it’s valid, then the branch after the AND is followed, otherwise that after the OR is followed.

This is equivalent though perhaps a bit less readable then

if [ $valid ]; then x=1; else x=0; fi

So you should be aware of the construct in case you ever run into it, but it’s arguably less readable than just listing out explicitly what you’re doing.

Thanks to experts-exchange for making me aware of this little tip.

Categories: Uncategorized Tags: , , , , , , ,
  1. zaphod
    December 16, 2010 at 5:10 pm


    echo $(( 1 == 1 ? 2 : 99 ))

    works perfectly in Bash.

    • i82much
      December 16, 2010 at 5:27 pm

      Good to know. Thanks.

      • suresh
        March 29, 2011 at 1:54 pm

        however echo $(( 1 == 1 ? 2 : 99 )) will work only for numeric variable.

  2. droope
    April 19, 2011 at 8:33 am


  3. December 5, 2011 at 6:08 am

    Great !! I t Works …

  4. bitten-by-bash
    April 18, 2013 at 1:46 am

    The equivalence of “if a; then b; else c; fi” and “a && b || c” is a fairly common misconception. The difference is that in the first case ‘a’ gets evaluated, and
    depending on its return value _either_ ‘b’ _or_ ‘c’ gets evaluated, but not both.
    In the second case, however, if ‘a’ has return value 0 (i.e. success/true), then
    ‘c’ can still be evaluated depending on the return value of ‘b’…

    • Nicholas Dunn
      April 18, 2013 at 8:12 am

      Is that true if it were (a && b) || c?

      • Stick
        May 30, 2013 at 7:21 am

        Yes, if a is true and b revaluates as false then c will be evaluated, which is nto the same as the if/then/else statement.

  1. January 13, 2012 at 8:04 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: