Back

28th May 2024

#Programming#Bash

If statements in Bash

Blog image

Like in other languages, in Bash we have IF conditional statement, which is key tool if you want to write more advanced scripts. It enables you to execute proper block of code, depends on certain conditions.

Basic syntax

Basic if statement

Blog image

If statement with else

Blog image

If statement with elif and else

Blog image

How to create conditions?

When you know basic syntax of if statements you probably wonder about how to determine conditions. To do that we must use special conditional operators properly.

Number conditional operators

Blog image

Blog image

String conditional operators

Blog image

Blog image

Directory and file conditional operators

Blog image

Blog image

Logical operators

Now, when we know more about conditional operators I can introduce logical operators. They are used to combine or negate conditions.

Blog image

Blog image

Blog image

Blog image

[ ] -> [[ ]]

I introduced basic if statements so far. We can handle with it basic and simple conditions. However, there is a more advanced version of if statement. It offers better support for conditional and logical operators, flexibility, security and susceptibility to syntax errors.

How to use this more advanced option? Only difference is that the condition must be between two square brackets instead of one.

Now I will show yousome examples, where traditional if statement won't work, but this more advanced will.

Comparing number of letters in strings (with < and >)

Blog image

Blog image

Blog image

Blog image

Checking if both files exists (with &&)

Blog image

Blog image

Blog image

Blog image

Summary

Thank you for reading this article! We discovered all the secrets that if statements hide. Remember, that using if statements in Bash is key to write scripts, which are able to react on various situations and conditions. It is also necessary tool to start write more complex scripts.

I hope that after reading this article you are able to create proper conditions and improve your scripts with usage of this tool. I also encourage you to start practise and play with if statements to master this extremely important concept.

Back to articles