if, then, else, elif – CloudSavvy IT

Posted on


Bash Shell

Programming in Bash may be enjoyable at occasions. Figuring out separate your if’s out of your else-if’s or elif’s as they’re referred to as in Bash, may be enjoyable too. Learn the way get your Bash conditionals proper.

Bash Conditionals: if, then, else, elif

In nearly as good as all coding languages, there are conditionals – conditional statements which permit one to check for a wide range of conditions. In most programming languages, a primary if assertion would enable one to check the standing or worth of a given programming variable. For instance, one might check if a variable is empty or not.

To be taught extra about Bash variables, you could wish to evaluate our Bash Functions and Local Variables article.

Bash is a full-blown Linux shell, and a complete programming language. It additionally consists of many extensions to the extra widespread conditional statements inside it’s scripting/programming language. For instance, one can check for the presence of recordsdata, to see if a grep -q assertion was profitable and so forth.

Moreover, one can specify advanced conditional statements, and even subshells proper contained in the if and so forth. conditional assertion itself. This makes Bash very appropriate for large information wrangling/mangling, textual content parsing and plenty of different DevOps-like duties.

This text will focus primarily on getting the conditionals proper, utilizing if...then, else, and elif statements. A future article will have a look at extra advanced check situations, utilizing subshells inside conditional statements and so forth.

Bash Conditional Testing: if..then…fi

Writing a conditional assertion in Bash is straightforward and simple. You’ll be able to even write them instantly on the Bash command line, with out utilizing a script:

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

Simple if example in Bash

The result is true, as 1 matches 1. Observe that the way in which to check equality between to gadgets is to make use of == and never =. That is the case in lots of languages and is commonly executed to keep away from, or clearly separate from, “task” (i.e setting a variable to a given worth).

Observe additionally that we terminate every conditional if assertion with a terminating fi (the reverse of if) assertion. This permits us to specify a number of traces after then then clause earlier than terminating the then part.

Bash Conditional Testing: else And Variables

Allow us to now put this into a bit of script, add an else part, and add some variable checks.

We outline check.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 by issuing chmod +x check.sh which units the executable flag for the check.sh script.

In-script if example using variables and an else clause

Contained in the script we set VAR1 and VAR2 to the worth of 1. We subsequent challenge an if assertion which compares the 2 variables, and echo true if the comparability is legitimate, and false if the comparability failed. The result’s an accurate true output.

Bash Conditional Testing: if Nesting, and Superior Checks

We will broaden the final instance a bit of additional, and verify for inequality utilizing != as a substitute of ==, add nested loops and use some Bash native superior variable checks on the similar time.

We outline 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: Both VAR1 (worth: '${VAR1}'), or VAR2 (worth: '${VAR2}'), or each, are empty!"
fi

On this script, we changed our hard-coded values of 1 for each VAR1 and VAR2 with two particular variables specifically ${1} and ${2}, which stand for the primary and second possibility/parameter, handed from the command line to the script. We make our script executable once more, and execute it with numerous fallacious possibility mixtures.

A more complex inequality if statement which also tests script variables

The -z code stands for verify if a parameter is empty or not. We negate the outcome (i.e. sure turns into no and no turns into sure, or fairly/higher true turns into false and false turns into true) by utilizing an exclamation mark (!) in entrance of the -z verify. We then additionally use an AND clause (i.e. either side of the AND clause must show true).

In different phrases, the way in which that you could possibly learn the if [ ! -z "${VAR1}" -a ! -z "${VAR2}" ]; line in pure language is Each VAR1 and VAR2 shouldn’t be empty. We will see that our variables are being checked accurately by this conditional assertion, as each time we attempt to move just one variable, or two variables the place one is empty, this system jumps to the else clause which studies on our incorrect script possibility utilization.

Lastly, inside the primary if conditional assertion, we’ve got a secondary (pc jargon: nested) conditional assertion. This assertion does our inequality verify by utilizing not equal (!=). Certain sufficient, once we move two completely different values specifically 1 and 2 to the script, the output is true: these numbers are unequal.

Bash Conditional Testing: elif

Whenever you begin growing extra advanced and deeply nested statements in Bash, you’ll quickly discover that there’s a case during which you might be branching deeper and deeper into nested code, and the code begins wanting extra advanced due to the a number of layers of depth. Usually, although not at all times, one can use an elif assertion in such circumstances. For instance:

#!/bin/bash

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

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

Having outlined this script as test3.sh, we make it executable and run it.

elif conditional statement example with two different implementations

The 2 code blocks do precisely the identical: they verify whether or not the worth handed as the primary choice to the script (1, 3 and 5 respectively) is much less then (-lt) the values 2, 4 and 6 in sequence. We see that the 2 blocks work precisely the identical.

Nonetheless, the second block of code, which employs the usage of elif statements (which can be learn as else if statements) as a substitute of else..if conditional assertion blocks. The second block of code isn’t solely shorter, it is usually cleaner, clearer and less difficult on the attention. Observe you can additionally mix else and elif statements together, in a nested vogue and so forth.

Conclusion

Writing Bash code is, was and can seemingly for fairly a while to return an fulfilling train for a lot of. Creating effectively crafted conditional statements is an integral and commonplace a part of this. On this brief tutorial, we checked out if, then, else, elif and fi statements. Utilizing the assorted conditional statements it is possible for you to to create nice and clear code. Get pleasure from!



Source link

Gravatar Image
I love to share everything with you

Leave a Reply

Your email address will not be published. Required fields are marked *