-1

I am automating a script in real-time and based on some variables' values I want to append different string versions into the script I am building. to simplify the case, here is an example:

someenvvar=true

and I want to have a condition on this boolean variable within an echo, so I would expect something like:

echo "podman run {$someenvvar == true ? --net=myhost : --net=anotherhost}" >> test_script but the above command gives me the following output inside the script:

podman run { == true ? --net=myhost : --net=anotherhost}

I need to check several conditions within the same echo command and thus I seek the shortest version of inlined if conditions (if exists).

I know I can use if [<condition>]; then <true statements> elseif <false statements> fi inside the script but that is not what I want because I want to fill the script in realtime and need to have online echo command with possibility to check multiple environment variables within it. Your insights are much appreciated.

shermakh
  • 117
  • 1
  • 7
  • 1
    bash does not have _boolean_ variables. A bash variable can hold a string, and also has arrays. You have to model your idea of a boolean somehow using strings. There is some builtin support which makes it easier to test, whether a string is empty or not, and also some support for dealing with strings which look like a whole number, and some people peruse this and represent, for instance, the concept of _false_ by an empty string, or by the string `0`, but of course you can also rule out your own mapping between the abstract idea of _true/false_ and a concrete string. – user1934428 Aug 30 '22 at 09:27

2 Answers2

1
$ someenvvar=0

$ echo podman run `[ $someenvvar = 1 ] && echo --net=myhost || echo --net=anotherhost`
podman run --net=anotherhost

$ someenvvar=1

$ echo podman run `[ $someenvvar = 1 ] && echo --net=myhost || echo --net=anotherhost`
podman run --net=myhost
xpusostomos
  • 1,309
  • 11
  • 15
0

I am not completely sure what you want to achieve, but maybe that helps you: You can put your command inside round parenthesis like this:

example=0    
echo "podman run $(if [ $example = 1 ]; then echo "a"; else echo "b"; fi)"
HFabi
  • 9
  • 3
  • thanks for the answer, it did eventually output `podman run b` but with "bash: [true]: command not found...", I believe that's the reason for why it headed to else statement – shermakh Aug 30 '22 at 08:33
  • 1
    I added whitespaces around the condition, know it should work as expected – HFabi Aug 30 '22 at 11:07
  • For what it's worth, `if [ true ]` works, but doesn't do what you think it does. "true" is not an empty string, so `if [ false ]` would do the same thing. The idiomatic way to say that is `if true` anyway. – tripleee Aug 31 '22 at 04:47
  • true can be replaced with any condition (I edited the code to make it more clear), please correct me if I am wrong here? – HFabi Aug 31 '22 at 17:11