{"id":165256,"date":"2021-01-28T16:00:40","date_gmt":"2021-01-28T13:00:40","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/if-then-else-elif-cloudsavvy-it\/"},"modified":"2021-01-28T16:00:40","modified_gmt":"2021-01-28T13:00:40","slug":"if-then-else-elif-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/if-then-else-elif-cloudsavvy-it\/","title":{"rendered":"#if, then, else, elif \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a42c9de65a74\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a42c9de65a74\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/if-then-else-elif-cloudsavvy-it\/#Bash_Conditionals_if_then_else_elif\" >Bash Conditionals: if, then, else, elif<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/if-then-else-elif-cloudsavvy-it\/#Bash_Conditional_Testing_ifthen%E2%80%A6fi\" >Bash Conditional Testing: if..then\u2026fi<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/if-then-else-elif-cloudsavvy-it\/#Bash_Conditional_Testing_else_And_Variables\" >Bash Conditional Testing: else And Variables<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/if-then-else-elif-cloudsavvy-it\/#Bash_Conditional_Testing_if_Nesting_and_Advanced_Checks\" >Bash Conditional Testing: if Nesting, and Advanced Checks<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/buradabiliyorum.com\/en\/if-then-else-elif-cloudsavvy-it\/#Bash_Conditional_Testing_elif\" >Bash Conditional Testing: elif<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/buradabiliyorum.com\/en\/if-then-else-elif-cloudsavvy-it\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#if, then, else, elif \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-4038\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/f1fee0a0a83b16d260ba2e862cb46eec\/p\/uploads\/2017\/07\/add8ac45.png\" alt=\"Bash Shell\" width=\"1400\" height=\"600\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Programming in Bash can be fun at times. Knowing how to separate your if\u2019s from your else-if\u2019s or elif\u2019s as they are called in Bash, can be fun too. Find out how get your Bash conditionals right.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Bash_Conditionals_if_then_else_elif\"><\/span>Bash Conditionals: if, then, else, elif<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>In as good as all coding languages, there are conditionals \u2013 conditional statements which allow one to test for a variety of situations. In most programming languages, a basic <code>if<\/code> statement would allow one to test the status or value of a given programming variable. For example, one could test if a variable is empty or not.<\/p>\n<p>To learn more about Bash variables, you may like to review our Bash Functions and Local Variables article.<\/p>\n<p>Bash is a full-blown Linux shell, and a comprehensive programming language. It also includes many extensions to the more common conditional statements within it\u2019s <a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">script<\/a>ing\/programming language. For example, one can test for the presence of files, to see if a <code>grep -q<\/code> statement was successful and so on.<\/p>\n<p>Additionally, one can specify complex conditional statements, and even subshells right inside the <code>if<\/code> etc. conditional statement itself. This makes Bash very suitable for big data wrangling\/mangling, text parsing and many other DevOps-like tasks.<\/p>\n<p>This article will focus mainly on getting the conditionals right, using <code>if...then<\/code>, <code>else<\/code>, and <code>elif<\/code> statements. A future article will look at more complex test conditions, using subshells inside conditional statements etc.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Bash_Conditional_Testing_ifthen%E2%80%A6fi\"><\/span>Bash Conditional Testing: <i>if..then\u2026fi<\/i><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Writing a conditional statement in Bash is easy and straightforward. You can even write them directly on the Bash command line, without using a script:<\/p>\n<pre>if [ \"1\" == \"1\" ]; then echo 'true'; fi&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9270\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/faf590f1d6430f6b21c6a787dbce8780\/p\/uploads\/2021\/01\/baadc2c4.png\" alt=\"Simple if example in Bash\" width=\"355\" height=\"50\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>The outcome is <i>true<\/i>, as <code>1<\/code> matches <code>1<\/code>. Note that the way to test equality between to items is to use <code>==<\/code> and not <code>=<\/code>. This is the case in many languages and is often done to avoid, or clearly separate from, \u201cassignment\u201d (i.e setting a variable to a given value).<\/p>\n<p>Note also that we terminate each conditional <code>if<\/code> statement with a terminating <code>fi<\/code> (the reverse of <i>if<\/i>) statement. This allows us to specify multiple lines after then <code>then<\/code> clause before terminating the <i>then section<\/i>.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Bash_Conditional_Testing_else_And_Variables\"><\/span>Bash Conditional Testing: <i>else<\/i> And Variables<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let us now put this into a little script, add an <code>else<\/code> section, and add some variable checks.<\/p>\n<p>We define <code>test.sh<\/code> as follows:<\/p>\n<pre>#!\/bin\/bash&#13;\n&#13;\nVAR1=1&#13;\nVAR2=1&#13;\n&#13;\nif [ \"${VAR1}\" == \"${VAR2}\" ]; then &#13;\n  echo 'true'&#13;\nelse &#13;\n  echo 'false'&#13;\nfi&#13;\n<\/pre>\n<p>Then, we make this little script executable by issuing <code>chmod +x test.sh<\/code> which sets the executable flag for the <code>test.sh<\/code> script.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9271\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/9db207680ea1c54d08f9f20b95293983\/p\/uploads\/2021\/01\/f3a8ed5e.png\" alt=\"In-script if example using variables and an else clause\" width=\"346\" height=\"256\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Inside the script we set <code>VAR1<\/code> and <code>VAR2<\/code> to the value of 1. We next issue an if statement which compares the two variables, and echo <code>true<\/code> if the comparison is valid, and <code>false<\/code> if the comparison failed. The result is a correct <code>true<\/code> output.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Bash_Conditional_Testing_if_Nesting_and_Advanced_Checks\"><\/span>Bash Conditional Testing: <i>if<\/i> Nesting, and Advanced Checks<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We can expand the last example a little further, and check for inequality using <code>!=<\/code> instead of <code>==<\/code>, add nested loops and use some Bash native advanced variable checks at the same time.<\/p>\n<p>We define <code>test2.sh<\/code> as follows:<\/p>\n<pre>#!\/bin\/bash&#13;\n&#13;\nVAR1=\"${1}\"&#13;\nVAR2=\"${2}\"&#13;\n&#13;\nif [ ! -z \"${VAR1}\" -a ! -z \"${VAR2}\" ]; then&#13;\n  if [ \"${VAR1}\" != \"${VAR2}\" ]; then &#13;\n    echo 'true'&#13;\n  else &#13;\n    echo 'false'&#13;\n  fi&#13;\nelse&#13;\n  echo \"Assert: Either VAR1 (value: '${VAR1}'), or VAR2 (value: '${VAR2}'), or both, are empty!\"&#13;\nfi&#13;\n<\/pre>\n<p>In this script, we replaced our hard-coded values of <code>1<\/code> for both <code>VAR1<\/code> and <code>VAR2<\/code> with two special variables namely <code>${1}<\/code> and <code>${2}<\/code>, which stand for <i>the first and second option\/parameter<\/i>, passed from the command line to the script. We make our script executable again, and execute it with various wrong option combinations.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9272\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/c5b4ae760508a0dc21b094602c6267d2\/p\/uploads\/2021\/01\/4ef83a4a.png\" alt=\"A more complex inequality if statement which also tests script variables\" width=\"806\" height=\"424\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>The <code>-z<\/code> code stands for <i>check if a parameter is empty or not<\/i>. We negate the result (i.e. yes becomes no and no becomes yes, or rather\/better true becomes false and false becomes true) by using an exclamation mark (<code>!<\/code>) in front of the <code>-z<\/code> check. We then also use an <i>AND<\/i> clause (i.e. both sides of the <i>AND<\/i> clause have to prove true).<\/p>\n<p>In other words, the way that you could read the <code>if [ ! -z \"${VAR1}\" -a ! -z \"${VAR2}\" ];<\/code> line in natural language is <i>Both VAR1 and VAR2 should not be empty<\/i>. We can see that our variables are being checked correctly by this conditional statement, as every time we try to pass only one variable, or two variables where one is empty, the program jumps to the <code>else<\/code> clause which reports on our incorrect script option usage.<\/p>\n<p>Finally, inside the first <code>if<\/code> conditional statement, we have a secondary (computer jargon: <i>nested<\/i>) conditional statement. This statement does our inequality check by using <i>not equal<\/i> (<code>!=<\/code>). Sure enough, when we pass two different values namely <code>1<\/code> and <code>2<\/code> to the script, the output is true: these numbers are unequal.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Bash_Conditional_Testing_elif\"><\/span>Bash Conditional Testing: <i>elif<\/i><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>When you start developing more complex and deeply nested statements in Bash, you will soon find that there is a case in which you are branching deeper and deeper into nested code, and the code starts looking more complex because of the multiple layers of depth. Often, though not always, one can use an <code>elif<\/code> statement in such cases. For example:<\/p>\n<pre>#!\/bin\/bash&#13;\n&#13;\nif [ \"${1}\" -lt 2 ]; then&#13;\n  echo \"less then 2\"&#13;\nelse&#13;\n  if [ \"${1}\" -lt 4 ]; then&#13;\n    echo \"less then 4\"&#13;\n  else&#13;\n    if [ \"${1}\" -lt 6 ]; then&#13;\n      echo \"less then 6\"&#13;\n    fi&#13;\n  fi&#13;\nfi&#13;\n&#13;\nif [ \"${1}\" -lt 2 ]; then&#13;\n  echo \"less then 2\"&#13;\nelif [ \"${1}\" -lt 4 ]; then&#13;\n  echo \"less then 4\"&#13;\nelif [ \"${1}\" -lt 6 ]; then&#13;\n  echo \"less then 6\"&#13;\nfi&#13;\n<\/pre>\n<p>Having defined this script as test3.sh, we make it executable and run it.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9273\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/48d1381490df1770a7aa56f7befa3c5f\/p\/uploads\/2021\/01\/f9754c39.png\" alt=\"elif conditional statement example with two different implementations\" width=\"274\" height=\"560\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>The two code blocks do exactly the same: they check whether the value passed as the first option to the script (<i>1, 3 and 5<\/i> respectively) is less then (<code>-lt<\/code>) the values <i>2, 4 and 6<\/i> in sequence. We see that the two blocks work exactly the same.<\/p>\n<p>However, the second block of code, which employs the use of <code>elif<\/code> statements (which can also be read as <i>else if<\/i> statements) instead of <i>else..if<\/i> conditional statement blocks. The second block of code is not only shorter, it is also cleaner, clearer and more easy on the eye. Note that you can also combine <code>else<\/code> and <code>elif<\/code> statements in combination, in a nested fashion etc.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Writing Bash code is, was and will likely for quite some time to come an enjoyable exercise for many. Creating well crafted conditional statements is an integral and commonplace part of this. In this short tutorial, we looked at <code>if<\/code>, <code>then<\/code>, <code>else<\/code>, <code>elif<\/code> and <code>fi<\/code> statements. Using the various conditional statements you will be able to create great and clean code. <strong>Enjoy!<\/strong>\n<\/div>\n<blockquote><p><strong><span style=\"color: #ff6600;\">If you liked the article, do not forget to share it with your friends. Follow us on\u00a0<span style=\"color: #ff0000;\"><a style=\"color: #ff0000;\" href=\"https:\/\/news.google.com\/publications\/CAAqBwgKMLG0nwswvr63Aw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">Google News<\/a><\/span>\u00a0too, click on the star and choose us from your favorites.<\/span><\/strong><\/p><\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/9269\/conditional-testing-in-bash-if-then-else-elif\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#if, then, else, elif \u2013 CloudSavvy IT&#8221; Programming in Bash can be fun at times. Knowing how to separate your if\u2019s from your else-if\u2019s or elif\u2019s as they are called in Bash, can be fun too. Find out how get your Bash conditionals right. Bash Conditionals: if, then, else, elif In as good as all&#8230;<\/p>\n","protected":false},"author":1,"featured_media":165257,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2017\/07\/add8ac45.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-165256","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/165256","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=165256"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/165256\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/165257"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=165256"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=165256"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=165256"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}