{"id":163564,"date":"2021-01-26T17:00:51","date_gmt":"2021-01-26T14:00:51","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/bash-functions-and-local-variables-cloudsavvy-it\/"},"modified":"2021-01-26T17:00:51","modified_gmt":"2021-01-26T14:00:51","slug":"bash-functions-and-local-variables-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/bash-functions-and-local-variables-cloudsavvy-it\/","title":{"rendered":"#Bash Functions and Local Variables \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_84 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-6a28b7c8cce94\" 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-6a28b7c8cce94\" 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\/bash-functions-and-local-variables-cloudsavvy-it\/#What_Are_Bash_Functions\" >What Are Bash Functions?<\/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\/bash-functions-and-local-variables-cloudsavvy-it\/#Simple_Bash_Function\" >Simple Bash Function<\/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\/bash-functions-and-local-variables-cloudsavvy-it\/#Passing_variables_to_Bash_functions\" >Passing variables to Bash functions<\/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\/bash-functions-and-local-variables-cloudsavvy-it\/#Local_variables_and_returning_values\" >Local variables and returning values<\/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\/bash-functions-and-local-variables-cloudsavvy-it\/#Wrapping_Up\" >Wrapping Up<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#Bash Functions and Local Variables \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<figure id=\"attachment_9253\" style=\"width: 700px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-9253 size-full\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/e425b19d3b89fc54ce7e13bec2c22370\/p\/uploads\/2021\/01\/6c23e628.png\" alt=\"\" width=\"700\" height=\"342\" data-crediturl=\"https:\/\/www.shutterstock.com\/image-photo\/developing-programming-coding-technologies-website-design-1016500210\" data-credittext=\"Shutterstock\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><figcaption class=\"wp-caption-text\"><span class=\"imagecredit\"><a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.shutterstock.com\/image-photo\/developing-programming-coding-technologies-website-design-1016500210\">Shutterstock<\/a><\/span><\/figcaption><\/figure>\n<p>This article will demonstrate how local variables functions are used and created in Bash. Creating Bash functions allows you to make your code more structural, and local variables help with security and avoiding coding mistakes. Dive in!<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"What_Are_Bash_Functions\"><\/span>What Are <i>Bash Functions<\/i>?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Alike to other coding languages, Bash allows you to create functions from within your code or <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>. A function can be defined to do a specific task, or set of tasks, and can be called easily and readily from within your main code by simply using the name given to the function.<\/p>\n<p>You can also nest function calls (calling a function from within another function), use local variables within the function and even pass variables back and forth with functions, or via using global variables. Let\u2019s explore.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Simple_Bash_Function\"><\/span>Simple Bash Function<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We define a test.sh with our text editor, as follows:<\/p>\n<pre>#!\/bin\/bash&#13;\n&#13;\nwelcome(){&#13;\necho \"welcome\"&#13;\n}&#13;\n&#13;\nwelcome&#13;\n<\/pre>\n<p>Subsequently, we make that file executable by adding the execute (<code>x<\/code>) property, and execute the script:<\/p>\n<pre>chmod +x test.sh&#13;\n.\/test.sh&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9149\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/c75d152b56089bae76d369f8840acb48\/p\/uploads\/2021\/01\/961bc952.png\" alt=\"A simple Bash function\" width=\"216\" height=\"204\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>We can see how the script first defines a <code>welcome()<\/code> function using the Bash idioms <code>function_name()<\/code>, and <code>{<\/code>\u2026<code>}<\/code> function wrappers. Finally, we call the function welcome by simply using it\u2019s name, <code>welcome<\/code>.<\/p>\n<p>When the script is executed, what happens in the background, is that the function definition is noted, but skipped (i.e. not executed), until a bit lower the function call <code>welcome<\/code> is hit, and which point the Bash interpreter executes the <code>welcome<\/code> function and returns to the line directly after the function calls afterwards, which in this case is the end of our script.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Passing_variables_to_Bash_functions\"><\/span>Passing variables to Bash functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We define a test2.sh with our favorite text editor (vi ;), as follows:<\/p>\n<pre>#!\/bin\/bash&#13;\n&#13;\nif [ -z \"${1}\" ]; then &#13;\n  echo \"One option required!\"&#13;\n  exit 1&#13;\nfi&#13;\n&#13;\nfunc1(){&#13;\n  echo \"${1}\"&#13;\n}&#13;\n&#13;\nfunc2(){&#13;\n  echo \"${2} ${1}\"&#13;\n}&#13;\n&#13;\nfunc1 \"${1}\"&#13;\nfunc2 \"a\" \"b\"&#13;\n<\/pre>\n<p>We again make our script executable by using <code>chmod +x test2.sh<\/code> and execute the same.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9150\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/dba0ebe451b6edef1cf85703a6c77379\/p\/uploads\/2021\/01\/1925adec.png\" alt=\"A more advanced Bash function with variable passing\" width=\"299\" height=\"426\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>The resulting output may look interesting, or even confusing at first. However, it is logical and easy to follow. The fist option passed to the script will, globally, be available from within the code as <code>${1}<\/code>, except inside functions, where <code>${1}<\/code> becomes the first parameter passed to the function, <code>${2}<\/code> the second etc.<\/p>\n<p>In other words, the global <code>${1}<\/code> variable (the first option passed to the script from the command line) is not available from within functions, where the meaning of the <code>${1}<\/code> variable changes to the first option passed to the function. Think hierarchy, or think about how a function could present a small script by itself and this will soon make sense.<\/p>\n<p>As a sidenote, one could also use <code>$1<\/code> instead of <code>${1}<\/code>, but I strongly encourage aspiring Bash coders to always surround variable names with <code>{<\/code> and <code>}<\/code>.<\/p>\n<p>The reason is that sometimes, when using variables in a string for example, the Bash interpreter is not able to <i>see<\/i> where a variable ends and part of the adjoining text may be taken to be part of the variable name where it is not, leading to unexpected output. It is also cleaner and clearer what the intention is, especially when it comes to arrays and special option flags.<\/p>\n<p>We thus start our program with the global <code>${1}<\/code> variable set to <code>\"first\"<\/code>. If you look at the calling of <code>func1<\/code>, you will see that we pass that variable onto the function, thus the <code>${1}<\/code> inside the function becomes whatever was in the <code>${1}<\/code> of the program, i.e. <code>\"first\"<\/code>, and this why the first line of output is indeed <code>first<\/code>.<\/p>\n<p>We then call <code>func2<\/code> and we pass two strings <code>\"a\"<\/code> and <code>\"b\"<\/code> to the function. These then become the <code>${1}<\/code> and <code>${2}<\/code> automatically inside the <code>func2<\/code> function. Inside the function, we print them in reverse, and our output matches nicely with <code>b a<\/code> as the second line of output.<\/p>\n<p>Finally, we also do a check at the top of our script which ensures that an option is actually passed to the <code>test2.sh<\/code> script by checking if <code>\"${1}\"<\/code> is empty or not using the <code>-z<\/code> test inside the <code>if<\/code> command. We exit the script with a non-zero exit code (<code>exit 1<\/code>) to indicate to any calling programs that something went amiss.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Local_variables_and_returning_values\"><\/span>Local variables and returning values<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>For our final example, we define a test3.sh script as follows:<\/p>\n<pre>#!\/bin\/bash&#13;\n&#13;\nfunc3(){&#13;\n  local REVERSE=\"$(echo \"${1}\" | rev)\"&#13;\n  echo \"${REVERSE}\"&#13;\n}&#13;\n&#13;\nINPUT=\"abc\"&#13;\nREVERSE=\"$(func3 \"${INPUT}\")\"&#13;\necho \"${REVERSE}\"&#13;\n<\/pre>\n<p>We again make it executable and execute the script. The output is <code>cba<\/code> as can be expected by scanning over the code and noting the variable names etc.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9151\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/25eb0d05f8d40f324af155f469df4871\/p\/uploads\/2021\/01\/7adb4762.png\" alt=\"Example with local variables and returning values\" width=\"333\" height=\"254\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/h2>\n<p>However, the code is complex and takes a little getting used to. Let\u2019s explore.<\/p>\n<p>First, we define a function <code>func3<\/code> in which we create a local variable named <code>REVERSE<\/code>. We assign a value to it by calling a subshell (<code>$()<\/code>), and from within this subshell we echo whatever was passed to the function (<code>${1}<\/code>) and pipe this output to the <code>rev<\/code> command.<\/p>\n<p>The <code>rev<\/code> command prints the input received from the pipe (or otherwise) in reverse. Also interesting to note here is that the <code>${1}<\/code> variable remains inside the subshell! It is past integrally.<\/p>\n<p>Next, still from within the <code>func3<\/code> function, we print the output. However, this output will not be sent to the screen, it rather will be captured by our function call itself and thus stored within the <i>\u2018global\u2019<\/i> <code>REVERSE<\/code> variable.<\/p>\n<p>We set our input to <code>\"abc\"<\/code>, call the <code>func3<\/code> function again from within a subshell, passing the <code>INPUT<\/code> variable, and assign the output to the <code>REVERSE<\/code> variable. Note that there is absolutely no connection between the <i>\u2018global\u2019<\/i> <code>REVERSE<\/code> variable and the <i>local<\/i> <code>REVERSE<\/code> variable inside the script.<\/p>\n<p>Whilst any global variable, including any <i>REVERSE<\/i> will be passed to the function, as soon as a local variable is defined with the same name, the local variable will be used. We can also prove and see this another small script test4.sh:<\/p>\n<pre>#!\/bin\/bash&#13;\n&#13;\nfunc3(){&#13;\n  local REVERSE=\"$(echo \"${1}\" | rev)\"&#13;\n  echo \"${REVERSE}\"&#13;\n}&#13;\n&#13;\nINPUT=\"abc\"&#13;\nREVERSE=\"test\"&#13;\nfunc3 \"${INPUT}\"&#13;\necho \"${REVERSE}\"&#13;\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-9152\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/8949997031f2d92601a126efb45aa700\/p\/uploads\/2021\/01\/cd037649.png\" alt=\"Bash function and local variable example exemplifying two of the learning points seen so far\" width=\"378\" height=\"288\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>When executed the output is <code>cba<\/code> and <code>test<\/code>. The <code>cba<\/code> is this time generated by the same <code>echo \"${REVERSE}\"<\/code> inside the <code>func3<\/code> function, but is this time output directly instead of captured in the code below as the <code>func3 \"${INPUT}\"<\/code> function is not called from within a subshell.<\/p>\n<p>This script highlights two learning points we covered earlier: firstly, that \u2013 even though we set the <code>REVERSE<\/code> variable to <code>\"test\"<\/code> inside the script before calling the <code>func3<\/code> function \u2013 that the <i>local<\/i> variable <code>REVERSE<\/code> takes over and is used instead of the <i>\u2018global\u2019<\/i> one.<\/p>\n<p>Secondly, that our <i>\u2018global\u2019<\/i> <code>REVERSE<\/code> variable retains it value even though there was a <i>local<\/i> variable with he same name used from within the called function <code>func3<\/code>.<\/p>\n<h2 role=\"heading\" aria-level=\"2\"><span class=\"ez-toc-section\" id=\"Wrapping_Up\"><\/span>Wrapping Up<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>As you can see, Bash functions, the passing of variables, as well as the use of local and semi-global variables makes the Bash scripting language versatile, easy to code, and gives you the possibility to define well structured code.<\/p>\n<p>Also noteworthy to mention here is that besides improved code readability and easy-of-use, using local variables provides additional security as variables will not be accessible outside of the context of a function etc. <strong>Enjoy functions and local variables whilst coding in Bash!<\/strong><\/p>\n<p>If you\u2019re interested in learning more about Bash, checkout our How to Correctly Parse File Names in Bash, and Using xargs in Combination With bash -c to Create Complex Commands.\n<\/p><\/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\/9148\/bash-functions-and-local-variables\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#Bash Functions and Local Variables \u2013 CloudSavvy IT&#8221; Shutterstock This article will demonstrate how local variables functions are used and created in Bash. Creating Bash functions allows you to make your code more structural, and local variables help with security and avoiding coding mistakes. Dive in! What Are Bash Functions? Alike to other coding languages,&#8230;<\/p>\n","protected":false},"author":1,"featured_media":163565,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2021\/01\/6c23e628.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-163564","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\/163564","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=163564"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/163564\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/163565"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=163564"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=163564"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=163564"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}