{"id":3349,"date":"2018-11-13T14:23:57","date_gmt":"2018-11-13T14:23:57","guid":{"rendered":"https:\/\/www.appservgrid.com\/paw92\/?p=3349"},"modified":"2018-11-17T14:09:54","modified_gmt":"2018-11-17T14:09:54","slug":"bash-for-loop-linuxize","status":"publish","type":"post","link":"https:\/\/www.appservgrid.com\/paw92\/index.php\/2018\/11\/13\/bash-for-loop-linuxize\/","title":{"rendered":"Bash For Loop | Linuxize"},"content":{"rendered":"<p>Loops are one of the fundamental concepts of programming languages. Loops are handy, if you want to run series of commands over and over again, until a condition situation is reached.<\/p>\n<p>In scripting languages such as Bash, loops are useful for automating repetitive tasks.<\/p>\n<p>There are 3 basic loop constructs in Bash scripting, for loop, while loop, and until loop.<\/p>\n<p>In this tutorial we will cover the basics of for loops in Bash as well as the break and continue statements to alter the flow of a loop.<\/p>\n<h2>The Standard Bash For Loop<\/h2>\n<p>The for loop iterates over a list of items and performs the given set of commands.<\/p>\n<p>The Bash for loop takes the following form:<\/p>\n<p>for item in [LIST]<br \/>\ndo<br \/>\n[COMMANDS]<br \/>\ndone<\/p>\n<p>The list can be a series of strings separated by spaces, range of numbers, output of a command, an array, and so on.<\/p>\n<h3>Loop over strings<\/h3>\n<p>In the example below the loop will iterate over each item of the list of strings and the variable element will be set to the current item.<\/p>\n<p>for element in Hydrogen Helium Lithium Beryllium<br \/>\ndo<br \/>\necho &#8220;Element: $element&#8221;<br \/>\ndone<\/p>\n<p>The loop will produce the following output:<\/p>\n<p>Element: Hydrogen<br \/>\nElement: Helium<br \/>\nElement: Lithium<br \/>\nElement: Beryllium<\/p>\n<h3>Loop over a number range<\/h3>\n<p>You can use the sequence expression to specify a range of numbers or characters by defining a start and the end point of the range. The sequence expression takes the following form:<\/p>\n<p>In the example below the loop will iterate through all numbers from 0 to 3.<\/p>\n<p>for i in<br \/>\ndo<br \/>\necho &#8220;Number: $i&#8221;<br \/>\ndoneNumber: 0<br \/>\nNumber: 1<br \/>\nNumber: 2<br \/>\nNumber: 3<\/p>\n<p>Starting from Bash 4, it is also possible to specify an increment when using ranges. The expression takes the following form:<\/p>\n<p>for i in<br \/>\ndo<br \/>\necho &#8220;Number: $i&#8221;<br \/>\ndoneNumber: 0<br \/>\nNumber: 5<br \/>\nNumber: 10<br \/>\nNumber: 15<br \/>\nNumber: 20<\/p>\n<h3>Loop over array elements<\/h3>\n<p>You can also use the for loop to iterate over all elements in an array:<\/p>\n<p>In the example below we are defining an array BOOKS and iterating over each element of the array.<\/p>\n<p>BOOKS=(&#8216;In Search of Lost Time&#8217; &#8216;Don Quixote&#8217; &#8216;Ulysses&#8217; &#8216;The Great Gatsby&#8217;)<\/p>\n<p>for book in &#8220;$&#8221;; do<br \/>\necho &#8220;Book: $book&#8221;<br \/>\ndoneBook: In Search of Lost Time<br \/>\nBook: Don Quixote<br \/>\nBook: Ulysses<br \/>\nBook: The Great Gatsby<\/p>\n<h2>The C-style Bash for loop<\/h2>\n<p>The syntax of the C-style for loop is taking the following form:<\/p>\n<p>for ((INITIALIZATION; TEST; STEP))<br \/>\ndo<br \/>\n[COMMANDS]<br \/>\ndone<\/p>\n<p>The INITIALIZATION part is executed only once when the loop starts. Then, the TEST part is evaluated. If it is false the for loop is terminated. If the TEST is true, commands inside the body of for loop are executed and the STEP part is updated.<\/p>\n<p>In the following code the loop stars by initializing i = 0, then before each iteration checks if i \u2264 10. If true it prints the current value of i and increment the variable i by 1 (i++) otherwise the loop terminates.<\/p>\n<p>for ((i = 0 ; i &lt;= 1000 ; i++)); do<br \/>\necho &#8220;Counter: $i&#8221;<br \/>\ndone<\/p>\n<p>The the loop iterates 1001 times and will produce the following output:<\/p>\n<p>Counter: 0<br \/>\nCounter: 1<br \/>\nCounter: 2<br \/>\n&#8230;<br \/>\nCounter: 998<br \/>\nCounter: 999<br \/>\nCounter: 1000<\/p>\n<h2>Break and Continue Statements<\/h2>\n<p>The break and continue statements can be used to control the loop execution.<\/p>\n<h3>Break Statement<\/h3>\n<p>The break statement terminates the current loop and passes program control to the statement that follows the terminated statement. It is usually used to terminate the loop when a certain condition is met.<\/p>\n<p>In the following example, the execution of the loop will be terminated once the current iterated item is equal to \u2018Lithium\u2019.<\/p>\n<p>for element in Hydrogen Helium Lithium Beryllium; do<br \/>\nif [[ &#8220;$element&#8221; == &#8216;Lithium&#8217; ]]; then<br \/>\nbreak<br \/>\nfi<br \/>\necho &#8220;Element: $element&#8221;<br \/>\ndone<\/p>\n<p>echo &#8216;All Done!&#8217;Element: Hydrogen<br \/>\nElement: Helium<br \/>\nAll Done!<\/p>\n<h3>Continue Statement<\/h3>\n<p>The continue statement exits the current iteration of a loop and passes program control to the next iteration of the loop.<\/p>\n<p>In the following example, we are iterating through a range of numbers and when the current iterated item is equal to \u20182\u2019 the continue statement will cause execution to return to the beginning of the loop and to continue with the next iteration.<\/p>\n<p>for i in ; do<br \/>\nif [[ &#8220;$i&#8221; == &#8216;2&#8217; ]]; then<br \/>\ncontinue<br \/>\nfi<br \/>\necho &#8220;Number: $i&#8221;<br \/>\ndoneNumber: 1<br \/>\nNumber: 3<br \/>\nNumber: 4<br \/>\nNumber: 5<\/p>\n<h2>Bash For Loop Examples<\/h2>\n<h3>Renaming files with spaces in the filename<\/h3>\n<p>The following example shows how to use the Bash for loop to rename all of the files in the current directory with a space in its names by replacing space to underscore.<\/p>\n<p>for file in * *; do<br \/>\nmv &#8220;$file&#8221; &#8220;$&#8221;<br \/>\ndone<\/p>\n<p>Let\u2019s break down the code line by line:<\/p>\n<ul>\n<li>The first line creates a for loop and iterates through a list of all files with a space in its name. The expression * * creates the list.<\/li>\n<li>The second line applies to each item of the list and moves the file to a new one replacing the space with an underscore (_). The part $ is using the <a href=\"https:\/\/www.gnu.org\/software\/bash\/manual\/html_node\/Shell-Parameter-Expansion.html\">shell parameter expansion<\/a> to replace a pattern within a parameter with a string.<\/li>\n<li>done indicates the end of the loop segment.<\/li>\n<\/ul>\n<h3>Changing file extension<\/h3>\n<p>The following example shows how to use the Bash for loop to rename all files ending with .jpeg in the current directory by replacing the file extension from .jpeg to .jpg.<\/p>\n<p>for file in *.jpeg; do<br \/>\nmv &#8212; &#8220;$file&#8221; &#8220;$.jpg&#8221;<br \/>\ndone<\/p>\n<p>Let\u2019s analyze the code line by line:<\/p>\n<ul>\n<li>The first line creates a for loop and iterates through a list of all files edging with .jpeg.<\/li>\n<li>The second line applies to each item of the list and moves the file to a new one replacing .jpeg with .jpg. The part $ is using the <a href=\"https:\/\/www.gnu.org\/software\/bash\/manual\/html_node\/Shell-Parameter-Expansion.html\">shell parameter expansion<\/a> to delete the .jpeg part from the filename.<\/li>\n<li>done indicates the end of the loop segment.<\/li>\n<\/ul>\n<h2>Conclusion<\/h2>\n<p>By now you should have a good understanding of how to use the bash for loop to iterate through lists.<\/p>\n<p>If you have any question or feedback feel free to leave a comment.<\/p>\n<p><a href=\"http:\/\/lxer.com\/module\/newswire\/ext_link.php?rid=262729\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Loops are one of the fundamental concepts of programming languages. Loops are handy, if you want to run series of commands over and over again, until a condition situation is reached. In scripting languages such as Bash, loops are useful for automating repetitive tasks. There are 3 basic loop constructs in Bash scripting, for loop, &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/www.appservgrid.com\/paw92\/index.php\/2018\/11\/13\/bash-for-loop-linuxize\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Bash For Loop | Linuxize&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-3349","post","type-post","status-publish","format-standard","hentry","category-linux"],"_links":{"self":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/3349","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/comments?post=3349"}],"version-history":[{"count":1,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/3349\/revisions"}],"predecessor-version":[{"id":3591,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/3349\/revisions\/3591"}],"wp:attachment":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/media?parent=3349"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/categories?post=3349"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/tags?post=3349"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}