Search code examples
bashshellif-statementshecho

Use if condition within an echo in shell


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.


Solution

  • $ 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