0

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.

  • 2
    The closing `}` required a preceding newline or semicolon. – glenn jackman Jan 05 '21 at 03:10
  • 1
    Note that `$(...)` command substitution strips all trailing newlines, so not necessary to `echo -n` – glenn jackman Jan 05 '21 at 03:11
  • @glennjackman Yes, I had it working with a bunch of semicolons in the line--I was simply wondering if there was a way for a single `echo` command to handle the conditional statement itself. Perhaps I should have showed the working solution I had in the question--sorry! I thought the example I gave would be more clear with respect to what I was curious about. I did not know that a single echo could handle multiple sets of quotation marks as jared_mamrot's answer showed, which is as good a solution as I was expecting. Also, thank you for the extra info on how command substitution works! :^) – user3334794 Jan 05 '21 at 03:46

1 Answers1

1

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"
jared_mamrot
  • 22,354
  • 4
  • 21
  • 46