قالب وردپرس درنا توس
Home / Tips and Tricks / if, then, else, elif – CloudSavvy IT

if, then, else, elif – CloudSavvy IT



Bash Shell

Programming in Bash can be fun at times. Knowing how to separate your if’s from your else-if’s or elif’s as they are called in Bash can also be fun. Find out how to get your Bash conditionals right.

Bash Conditionals: if, then, else, elif

In almost all coding languages ​​there are conditionals ̵

1; conditional statements that allow testing for a variety of situations. In most programming languages ​​there is a foundation if statement would allow someone to test the status or value of a particular programming variable. For example, one could test whether a variable is empty or not.

For more information on Bash variables, read our article Bash functions and local variables.

Bash is a complete Linux shell and a comprehensive programming language. It also contains many extensions to the more general conditional statements in the script / programming language. For example, one can test for the presence of files to see if a grep -q statement was successful and so on.

In addition, one can specify complex conditional statements, and even subshells within it if etc. conditional statement itself. This makes Bash great for big data wrangling / mangling, text parsing and many other DevOps-like tasks.

This article will mainly focus on getting the conditionals correct, usage if...then, else, and elif explanations. A future article will look at more complex test conditions, using subshells within conditional statements etc.

Bash conditionally testing: if..then … fi

Writing a conditional statement in Bash is simple and straightforward. You can even write them directly on the Bash command line, without using a script:

if [ "1" == "1" ]; then echo 'true'; fi

Simple as an example in Bash

The result is true, such as 1 matches 1. Note that the way to test equality between two items is to use == and not =. This is the case in many languages ​​and is often done to avoid or clearly separate “assignment” (ie, setting a variable to a particular value).

Also note that we end every conditional if statement with a terminating fi (the reverse of as) statement. This allows us to specify multiple rules afterwards then clause before the then section.

Bash conditionally testing: different And variables

Now let’s put this in a little script, one else section, and add some variable controls.

We define test.sh as follows:

#!/bin/bash

VAR1=1
VAR2=1

if [ "${VAR1}" == "${VAR2}" ]; then 
  echo 'true'
else 
  echo 'false'
fi

Then we make this little script executable through chmod +x test.sh which sets the executable flag for the test.sh script.

In script as an example with variables and an else clause

Within the script we have set VAR1 and VAR2 to the value of 1. Next, we issue an if statement comparing the two variables and echo true if the equation is valid, and false if the comparison fails. The result is correct true output.

Bash conditionally testing: as Nesting and advanced controls

We can extend the last example a bit further, and with the help of != instead of ==, add nested loops and use some Bash native advanced variable controls at the same time.

We define test2.sh as follows:

#!/bin/bash

VAR1="${1}"
VAR2="${2}"

if [ ! -z "${VAR1}" -a ! -z "${VAR2}" ]; then
  if [ "${VAR1}" != "${VAR2}" ]; then 
    echo 'true'
  else 
    echo 'false'
  fi
else
  echo "Assert: Either VAR1 (value: '${VAR1}'), or VAR2 (value: '${VAR2}'), or both, are empty!"
fi

In this script, we have our hard-coded values ​​of 1 for both VAR1 and VAR2 with two special variables namely ${1} and ${2}, they stand for the first and second option / parameter, passed from the command line to the script. We make our script executable again and run it with various wrong option combinations.

A more complex inequality if statement that also tests script variables

The -z code stands for check if a parameter is empty or not. We deny the result (i.e. yes becomes no and no becomes yes, or rather / better said true becomes false and false becomes true) by using an exclamation point (!) for the -z to check. We therefore use one AND clause (i.e. both sides of the AND clause must prove to be true).

In other words, the way you do it if [ ! -z "${VAR1}" -a ! -z "${VAR2}" ]; line is in natural language Both VAR1 and VAR2 cannot be empty. We can see that our variables are properly checked by this conditional statement, because every time we try to pass just one variable, or two variables one of which is empty, the program jumps to the else clause reporting our improper use of script options.

Finally, in the first if conditional statement, we have a secondary (computer jargon: nestedconditional statement. This statement checks our inequality by using not equal (!=). And yes, if we pass on two different values 1 and 2 to the script, the output is true: these numbers are unequal.

Bash conditionally testing: elif

When you start developing more complex and deeply nested statements in Bash, you will quickly notice that there is a case where you branch deeper and deeper into nested code, and the code looks more complex due to the multiple depth layers. Often, but not always, a elif statement in such cases. For example:

#!/bin/bash

if [ "${1}" -lt 2 ]; then
  echo "less then 2"
else
  if [ "${1}" -lt 4 ]; then
    echo "less then 4"
  else
    if [ "${1}" -lt 6 ]; then
      echo "less then 6"
    fi
  fi
fi

if [ "${1}" -lt 2 ]; then
  echo "less then 2"
elif [ "${1}" -lt 4 ]; then
  echo "less then 4"
elif [ "${1}" -lt 6 ]; then
  echo "less then 6"
fi

After we define this script as test3.sh, we make it executable and run it.

elif conditional statement example with two different implementations

The two code blocks do exactly the same thing: they check if the value was passed to the script as the first option (1, 3 and 5 respectively) is less than (-lt) the values 2, 4 and 6 in a row. We see that the two blocks work exactly the same.

The second block of code, which uses the elif statements (which can also be read as otherwise as statements) instead of otherwise..if conditional statement blocks. The second block of code is not only shorter, but also cleaner, clearer and easier on the eye. Note that you can also combine else and elif statements in combination, in a nested manner, etc.

Conclusion

Writing Bash code is, was, and will likely be an enjoyable exercise for many for a long time to come. Making well-drafted conditional statements is an integral and everyday part of this. In this short tutorial we looked at if, then, else, elif and fi explanations. Using the various conditional statements, you can create great and clean code. To enjoy!


Source link