Search code examples
bashconditional-statementsecho

Can a conditional statement be used inside a command in bash?


Can a conditional statement be inserted in, for example, a print command like echo with bash?

E.g. (does not work)

$ cat t.sh
#!/bin/bash

string1="It's a "
string2opt1="beautiful"
string2opt2="gross"
string3=" day."

read c

echo -n "$string1 $( [[ $c -eq 0 ]] && { echo -n "$string2opt1" } || { echo "$string2opt2" } ) $string3"

I know that this is possible with semicolons/non-one-liners; I am just wondering if there is a more elegant or accepted way of doing this.


Solution

  • To clarify, you want to achieve this:

    #!/bin/bash
    
    string1="It's a"
    string2opt1="beautiful"
    string2opt2="gross"
    string3="day."
    
    read -r c
    
    if [[ $c -eq 0 ]]; then
      echo "$string1" "$string2opt1" "$string3"
    else
      echo "$string1" "$string2opt2" "$string3"
    fi
    

    but in a one-liner. Does this work for you?

    #!/bin/bash
    
    string1="It's a"
    string2opt1="beautiful"
    string2opt2="gross"
    string3="day."
    
    read -r c
    
    echo "$string1" "$([[ $c -eq 0 ]] && echo "$string2opt1" || echo "$string2opt2")" "$string3"