Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading