Home > All, Linux > Ternary operator for bash scripting.

Ternary operator for bash scripting.

I was curious whether or not ternary operations are possible in bash or not. It turns out they are but only for numeric comparisons. So what if you wanted to compare whether a string is empty if you cannot use a string comparison (-Z or -n for example)? Use the string’s length.

As always with Linux, there’s a plethora of ways to do what I am doing below, so this is just an example for your reference:

function check_mounted () {
    local result=`df | grep $1`
    echo $((${#result} > 0 ? 1 : 0))
Categories: All, Linux
  1. Volker Börchers
    May 29th, 2013 at 10:44 | #1

    This solution is broken since in the shell you should use return/exit codes (0 for true) for boolean values:

    if check_mounted “volume”; then
    # volume is mounted

    But your function will always return true since echo (the last executed command) will always succeed.

    As grep (as all well designed unix commands) uses return code to signal a match the best way to implement check_mounted is:

    function check_mounted () {
    df | grep “$1” >/dev/null

  2. September 26th, 2013 at 02:48 | #2


  1. No trackbacks yet.