10.1. Loops

Техника

In this article, I will take you through 15 Practical Bash for loop Examples in Linux/Unix for Beginners. If you are using Bash Scripting in Linux from long time then you might be aware of bash for loop and its usages. So in this article I thought to explain some real world examples which will help you understand some of the use cases that you might encounter.

For Loop is used in Bash Scripting to run the same piece of code multiple times. You can either run same piece of code in the same Server multiple times or same code multiple times in multiple Servers. It can be used either way depends on your requirement. We will understand more about its usages as we go through this article.

There are two types of bash for loops available. One using the “in” keyword with list of values, another using the C programming like syntax.

This article is part of our on-going bash tutorial series.

This explains both of the bash for loop methods, and provides 12 different examples on how to use the bash for loop in your shell scripts.

Bookmark this article for future reference, as this is the only article you would ever need to refer on how to use bash for loops with examples.

Содержание
  1. Method 1: Bash For Loop using “in” and list of values
  2. Method 2: Bash For Loop using C like syntax
  3. 1. Static values for the list after “in” keyword
  4. 2. Variable for the list after “in” keyword
  5. 3. Don’t specify the list; get it from the positional parameters
  6. 4. Unix command output as list values after “in” keyword
  7. 5. Loop through files and directories in a for loop
  8. 6. Break out of the for loop
  9. 7. Continue from the top of the for loop
  10. 8. Bash for loop using C program syntax
  11. 9. Infinite Bash for loop
  12. 10. Using comma in the bash C-style for loop
  13. 11. Range of numbers after “in” keyword
  14. 12. Range of numbers with increments after “in” keyword
  15. Why are loops useful?
  16. Looping code example
  17. With and without a loop
  18. Looping through a collection
  19. The for…of loop
  20. map() and filter()
  21. The standard for loop
  22. Calculating squares
  23. Looping through collections with a for loop
  24. Exiting loops with break
  25. Skipping iterations with continue
  26. while and do…while
  27. Active learning: Launch countdown
  28. Active learning: Filling in a guest list
  29. Which loop type should you use?
  30. Test your skills!
  31. Conclusion
  32. See also
  33. Bash For Loop Syntax
  34. Example 1: How to Sync Time in multiple servers using Bash For Loop in Linux
  35. Example 2: How to Check next 5 CPU Load Average using Bash For Loop in Linux
  36. Example 3: How to check the processes using maximum swap memory in Linux
  37. Example 4: How to convert all rows into columns based on Colon(:) separator
  38. Example 5: How to convert all rows into columns based on Comma(,) field separator
  39. Example 6: How to Check the OS Version of Multiple Servers using bash for loop in Linux
  40. Example 7: How to Check the Memory Stats using bash for loop in Linux
  41. Example 8: How to Find the Private IP of AWS EC2 Instance using bash for loop
  42. Example 9: How to Create a File in Multiple Servers using Bash For Loop in Linux
  43. Example 10: How to start an application in multiple Linux Servers
  44. Example 11: How to check disk space of multiple Linux Servers
  45. Example 12: How to Check Kernel Version of Multiple Linux Servers
  46. Example 13: How to Find the total number of CPUs in Multiple Servers using bash for loop in Linux
  47. Example 14: How to Check SELinux Status in Multiple Servers using bash for loop in Linux
  48. Example 15: How to Check the Service Status in Multiple Servers using bash for loop in Linux

Method 1: Bash For Loop using “in” and list of values

for varname in list
do
 command1
 command2
 ..
done

In the above syntax:

  • for, in, do and done are keywords
  • “list” contains list of values. The list can be a variable that contains several words separated by spaces. If list is missing in the for statement, then it takes the positional parameter that were passed into the shell.
  • varname is any Bash variable name.

In this form, the for statement executes the commands enclosed in a body, once for each item in the list. For example, if the list of values contains 5 items, the for loop will be executed a total of 5 times, once for each item in the list. The current item from the list will be stored in a variable “varname” each time through the loop. This “varname” can be processed in the body of the for loop.

Method 2: Bash For Loop using C like syntax

The second form of the for loop is similar to the for loop in “C” programming language, which has three expressions (initialization, condition and updation).

for (( expr1; expr2; expr3 ))
do
 command1
 command2
 ..
done

In the above bash for command syntax,

  • Before the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop.
  • All the statements between do and done are executed repeatedly until the value of expr2 is TRUE.
  • After each iteration of the loop, expr3 is evaluated. This is usually used to increment a loop counter.

1. Static values for the list after “in” keyword

$ cat for1.sh
i=1
for day in Mon Tue Wed Thu Fri
do
 echo "Weekday $((i++)) : $day"
done

$ ./for1.sh
Weekday 1 : Mon
Weekday 2 : Tue
Weekday 3 : Wed
Weekday 4 : Thu
Weekday 5 : Fri

Caution: The list of values should not be separated by comma (Mon, Tue, Wed, Thu, Fri). The comma will be treated as part of the value. i.e Instead of “Mon”, it will use “Mon,” as value as shown in the example below.

$ cat for1-wrong1.sh
i=1
for day in Mon, Tue, Wed, Thu, Fri
do
 echo "Weekday $((i++)) : $day"
done

$ ./for1-wrong1.sh
Weekday 1 : Mon,
Weekday 2 : Tue,
Weekday 3 : Wed,
Weekday 4 : Thu,
Weekday 5 : Fri

Caution: The list of values should not be enclosed in a double quote. (“Mon Tue Wed Thu Fri”). If you enclose in double quote, it will be treated as a single value (instead of 5 different values), as shown in the example below.

$ cat for1-wrong2.sh
i=1
for day in "Mon Tue Wed Thu Fri"
do
 echo "Weekday $((i++)) : $day"
done

$ ./for1-wrong2.sh
Weekday 1 : Mon Tue Wed Thu Fri

2. Variable for the list after “in” keyword

$ cat for2.sh
i=1
weekdays="Mon Tue Wed Thu Fri"
for day in $weekdays
do
 echo "Weekday $((i++)) : $day"
done

$ ./for2.sh
Weekday 1 : Mon
Weekday 2 : Tue
Weekday 3 : Wed
Weekday 4 : Thu
Weekday 5 : Fri

Caution: As a best practice, you should always quote the bash variables when you are referring it. There are few exceptions to this best practice rule. This is one of them. If you double quote the variable in this for loop, the list of values will be treated as single value. Lot of people fall into this trap. Be careful and do not double quote your variable in the for loop.

$ cat for2-wrong.sh
i=1
weekdays="Mon Tue Wed Thu Fri"
for day in "$weekdays"
do
 echo "Weekday $((i++)) : $day"
done

$ ./for2-wrong.sh
Weekday 1 : Mon Tue Wed Thu Fri

3. Don’t specify the list; get it from the positional parameters

$ cat for3.sh
i=1
for day
do
 echo "Weekday $((i++)) : $day"
done

$ ./for3.sh Mon Tue Wed Thu Fri
Weekday 1 : Mon
Weekday 2 : Tue
Weekday 3 : Wed
Weekday 4 : Thu
Weekday 5 : Fri

Caution: Please be careful if you use this method. You should not include the keyword “in” in the for loop. If you leave the keyword “in” without any values, it will not use the positional parameter as shown below. It will not go inside the loop. i.e for loop will never get executed as shown in the example below.

$ cat for3-wrong.sh
i=1
for day in
do
 echo "Weekday $((i++)) : $day"
done

$ ./for3-wrong.sh Mon Tue Wed Thu Fri

Note: Refer to our earlier article to understand more about bash positional parameters.

4. Unix command output as list values after “in” keyword

You can use the output of any UNIX / Linux command as list of values to the for loop by enclosing the command in back-ticks ` ` as shown below.

$ cat for4.sh
i=1
for username in `awk -F: '{print $1}' /etc/passwd`
do
 echo "Username $((i++)) : $username"
done

$ ./for4.sh
Username 1 : ramesh
Username 2 : john
Username 3 : preeti
Username 4 : jason
..

5. Loop through files and directories in a for loop

To loop through files and directories under a specific directory, just cd to that directory, and give * in the for loop as shown below.

$ cat for5.sh
i=1
cd ~
for item in *
do
 echo "Item $((i++)) : $item"
done

$ ./for5.sh
Item 1 : positional-parameters.sh
Item 2 : backup.sh
Item 3 : emp-report.awk
Item 4 : item-list.sed
Item 5 : employee.db
Item 8 : storage
Item 9 : downloads

Usage of * in the bash for loop is similar to the file globbing that we use in the linux command line when we use ls command (and other commands).

cd ~
ls *
$ ls -1 /etc/[abcd]*.conf
/etc/asound.conf
/etc/autofs_ldap_auth.conf
/etc/cas.conf
/etc/cgconfig.conf
/etc/cgrules.conf
/etc/dracut.conf

The same argument that is used in the ls command above, can be used in a bash for loop, as shown in the example below.

$ cat for5-1.sh
i=1
for file in /etc/[abcd]*.conf
do
 echo "File $((i++)) : $file"
done

$ ./for5-1.sh
File 1 : /etc/asound.conf
File 2 : /etc/autofs_ldap_auth.conf
File 3 : /etc/cas.conf
File 4 : /etc/cgconfig.conf
File 5 : /etc/cgrules.conf
File 6 : /etc/dracut.conf

6. Break out of the for loop

You can break out of a for loop using ‘break’ command as shown below.

$ cat for6.sh
i=1
for day in Mon Tue Wed Thu Fri
do
 echo "Weekday $((i++)) : $day"
 if [ $i -eq 3 ]; then
   break;
 fi
done

$ ./for6.sh
Weekday 1 : Mon
Weekday 2 : Tue

7. Continue from the top of the for loop

Under certain conditions, you can ignore the rest of the commands in the for loop, and continue the loop from the top again (for the next value in the list), using the continue command as shown below.

$ cat for7.sh
i=1
for day in Mon Tue Wed Thu Fri Sat Sun
do
 echo -n "Day $((i++)) : $day"
 if [ $i -eq 7 -o $i -eq 8 ]; then
   echo " (WEEKEND)"
   continue;
 fi
 echo " (weekday)"
done

$ ./for7.sh
Day 1 : Mon (weekday)
Day 2 : Tue (weekday)
Day 3 : Wed (weekday)
Day 4 : Thu (weekday)
Day 5 : Fri (weekday)
Day 6 : Sat (WEEKEND)
Day 7 : Sun (WEEKEND)

8. Bash for loop using C program syntax

$ cat for8.sh
for (( i=1; i <= 5; i++ ))
do
 echo "Random number $i: $RANDOM"
done

$ ./for8.sh
Random number 1: 23320
Random number 2: 5070
Random number 3: 15202
Random number 4: 23861
Random number 5: 23435

9. Infinite Bash for loop

When you don’t provide the start, condition, and increment in the bash C-style for loop, it will become infinite loop. You need to press Ctrl-C to stop the loop.

$ cat for9.sh
i=1;
for (( ; ; ))
do
   sleep $i
   echo "Number: $((i++))"
done

Like we said above, press Ctrl-C to break out of this bash infinite for loop example.

$ ./for9.sh
Number: 1
Number: 2
Number: 3

10. Using comma in the bash C-style for loop

In the bash c-style loop, apart from increment the value that is used in the condition, you can also increment some other value as shown below.

Дополнительно:  Specs

In the initialize section, and the increment section of the bash C-style for loop, you can have multiple value by separating with comma as shown below.

$ cat for10.sh
for ((i=1, j=10; i <= 5 ; i++, j=j+5))
do
 echo "Number $i: $j"
done

$ ./for10.sh
Number 1: 10
Number 2: 15
Number 3: 20
Number 4: 25
Number 5: 30

11. Range of numbers after “in” keyword

You can loop through using range of numbers in the for loop “in” using brace expansion.

$ cat for11.sh
for num in {1..10}
do
 echo "Number: $num"
done

$ ./for11.sh
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
...

12. Range of numbers with increments after “in” keyword

$ cat for12.sh
for num in {1..10..2}
do
 echo "Number: $num"
done

$ ./for12.sh
Number: 1
Number: 3
Number: 5
Number: 7
Number: 9

PS: Don’t forget to bookmark this article for your future reference.

Programming languages are very useful for rapidly completing repetitive tasks, from multiple basic calculations to just about any other situation where you’ve got a lot of similar items of work to complete. Here we’ll look at the loop structures available in JavaScript that handle such needs.

Why are loops useful?

Loops are all about doing the same thing over and over again. Often, the code will be slightly different each time round the loop, or the same code will run but with different variables.

Looping code example

Suppose we wanted to draw 100 random circles on a <canvas> element (press the Update button to run the example again and again to see different random sets):

Update 
 
   100%
   inherit
   #ddd


 
   block


 
   0


 
   absolute
   5px
   5px

Here’s the JavaScript code that implements this example:

 btn  document
 canvas  document
 ctx  canvas

document   
  canvaswidth  documentdocumentElementclientWidth
  canvasheight  documentdocumentElementclientHeight


  
   MathMath  number


  
  ctx  canvaswidth canvasheight
    i   i   i 
    ctx
    ctxfillStyle  
    ctx
      canvaswidth
      canvasheight
      
      
        Math
    
    ctx
  


btn draw

With and without a loop

You don’t have to understand all the code for now, but let’s look at the part of the code that actually draws the 100 circles:

  i   i   i 
  ctx
  ctxfillStyle  
  ctx
    canvaswidth
    canvasheight
    
    
      Math
  
  ctx

  • random(x), defined earlier in the code, returns a whole number between 0 and x-1.

You should get the basic idea — we are using a loop to run 100 iterations of this code, each one of which draws a circle in a random position on the page.
The amount of code needed would be the same whether we were drawing 100 circles, 1000, or 10,000.
Only one number has to change.

ctx
ctxfillStyle  
ctx
  canvaswidth
  canvasheight
  
  
    Math

ctx

This would get very boring and difficult to maintain.

Looping through a collection

Most of the time when you use a loop, you will have a collection of items and want to do something with every item.

One type of collection is the Array, which we met in the Arrays chapter of this course.
But there are other collections in JavaScript as well, including Set and Map.

The for…of loop

 cats       

  cat  cats 
  consolecat

In this example, for (const cat of cats) says:

  1. Given the collection cats, get the first item in the collection.
  2. Assign it to the variable cat and then run the code between the curly brackets {}.
  3. Get the next item, and repeat (2) until you’ve reached the end of the collection.

map() and filter()

JavaScript also has more specialized loops for collections, and we’ll mention two of them here.

You can use map() to do something to each item in a collection and create a new collection containing the changed items:

  
   string


 cats       

 upperCats  catstoUpper

consoleupperCats

Here we pass a function into cats.map(), and map() calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array. In this case the function we provide converts the item to uppercase, so the resulting array contains all our cats in uppercase:

[ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]

You can use filter() to test each item in a collection, and create a new collection containing only items that match:

  
   cat


 cats       

 filtered  catslCat

consolefiltered

This looks a lot like map(), except the function we pass in returns a boolean: if it returns true, then the item is included in the new array.
Our function tests that the item starts with the letter «L», so the result is an array containing only cats whose names start with «L»:

[ "Leopard", "Lion" ]

Note that map() and filter() are both often used with function expressions, which we will learn about in the Functions module.
Using function expressions we could rewrite the example above to be much more compact:

 cats       

 filtered  cats  cat
consolefiltered

The standard for loop

 initializer condition finalexpression 
  // code to run

Here we have:

  1. The keyword for, followed by some parentheses.
  2. Inside the parentheses we have three items, separated by semicolons:
    1. An initializer — this is usually a variable set to a number, which is incremented to count the number of times the loop has run.
      It is also sometimes referred to as a counter variable.
    2. A condition — this defines when the loop should stop looping.
      This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.
    3. A final-expression — this is always evaluated (or run) each time the loop has gone through a full iteration.
      It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where the condition is no longer true.
  3. Some curly braces that contain a block of code — this code will be run each time the loop iterates.

Calculating squares

Let’s look at a real example so we can visualize what these do more clearly.

Calculate
Clear

 results  document

  
    i   i   i 
     newResult  
    resultstextContent  
  
  resultstextContent  


 calculateBtn  document
 clearBtn  document

calculateBtn calculate
clearBtn   resultstextContent  

This code calculates squares for the numbers from 1 to 9, and writes out the result. The core of the code is the for loop that performs the calculation.

Let’s break down the for (let i = 1; i < 10; i++) line into its three pieces:

  1. let i = 1: the counter variable, i, starts at 1. Note that we have to use let for the counter, because we’re reassigning it each time we go round the loop.
  2. i < 10: keep going round the loop for as long as i is smaller than 10.
  3. i++: add one to i each time round the loop.

Inside the loop, we calculate the square of the current value of i, that is: i * i. We create a string expressing the calculation we made and the result, and add this string to the output text. We also add \n, so the next string we add will begin on a new line. So:

  1. During the first run, i = 1, so we will add 1 x 1 = 1.
  2. During the second run, i = 2, so we will add 2 x 2 = 4.
  3. And so on…
  4. When i becomes equal to 10 we will stop running the loop and move straight to the next bit of code below the loop, printing out the Finished! message on a new line.

Looping through collections with a for loop

 cats       

  cat  cats 
  consolecat

We could rewrite that code like this:

 cats       

  i   i  catslength i 
  consolecatsi

In this loop we’re starting i at 0, and stopping when i reaches the length of the array.
Then inside the loop, we’re using i to access each item in the array in turn.

  • you might start i at 1, forgetting that the first array index is zero, not 1.
  • you might stop at i <= cats.length, forgetting that the last array index is at length - 1.

Sometimes you still need to use a for loop to iterate through an array.
For example, in the code below we want to log a message listing our cats:

 cats    

 myFavoriteCats  "My cats are called "

  cat  cats 
  myFavoriteCats  


consolemyFavoriteCats // "My cats are called Pete, Biggles, Jasmine, "

The final output sentence isn’t very well-formed:

My cats are called Pete, Biggles, Jasmine,

We’d prefer it to handle the last cat differently, like this:

My cats are called Pete, Biggles, and Jasmine.

But to do this we need to know when we are on the final loop iteration, and to do that we can use a for loop and examine the value of i:

 cats    

 myFavoriteCats  "My cats are called "

  i   i  catslength i 
   i  catslength   
    // We are at the end of the array
    myFavoriteCats  
    
    myFavoriteCats  
  


consolemyFavoriteCats // "My cats are called Pete, Biggles, and Jasmine."

Exiting loops with break

If you want to exit a loop before all the iterations have been completed, you can use the break statement.
We already met this in the previous article when we looked at switch statements — when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves on to the code after it.

Say we wanted to search through an array of contacts and telephone numbers and return just the number we wanted to find?
First, some simple HTML — a text <input> allowing us to enter a name to search for, a <button> element to submit a search, and a <p> element to display the results in:

Search by contact name: 
   
Search


Now on to the JavaScript:

 contacts  
  
  
  
  
  

 para  document
 input  document
 btn  document

btn   
   searchName  inputvalue
  inputvalue  
  input
  paratextContent  
    contact  contacts 
     splitContact  contact
     splitContact  searchName 
      paratextContent  
      
    
  
   paratextContent   
    paratextContent  "Contact not found."
  

  1. First of all, we have some variable definitions — we have an array of contact information, with each item being a string containing a name and phone number separated by a colon.
  2. Next, we attach an event listener to the button (btn) so that when it is pressed some code is run to perform the search and return the results.
  3. We store the value entered into the text input in a variable called searchName, before then emptying the text input and focusing it again, ready for the next search.
    Note that we also run the toLowerCase() method on the string, so that searches will be case-insensitive.
  4. Now on to the interesting part, the for...of loop:
    1. Inside the loop, we first split the current contact at the colon character, and store the resulting two values in an array called splitContact.
    2. We then use a conditional statement to test whether splitContact[0] (the contact’s name, again lower-cased with toLowerCase()) is equal to the inputted searchName.
      If it is, we enter a string into the paragraph to report what the contact’s number is, and use break to end the loop.
  5. After the loop, we check whether we set a contact, and if not we set the paragraph text to «Contact not found.».
Дополнительно:  Empire silver root 120x278 lapp 600180000015 керамогранит

Skipping iterations with continue

The continue statement works similarly to break, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop.
Let’s look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).

The HTML is basically the same as the last example — a simple numeric input, and a paragraph for output.

Enter number: 
   
Generate integer squares

Output:

The JavaScript is mostly the same too, although the loop itself is a bit different:

 para  document
 input  document
 btn  document

btn   
  paratextContent  
   num  inputvalue
  inputvalue  
  input
    i   i  num i 
     sqRoot  Mathi
     MathsqRoot  sqRoot 
      
    
    paratextContent  
  

Here’s the output:

  1. In this case, the input should be a number (num). The for loop is given a counter starting at 1 (as we are not interested in 0 in this case), an exit condition that says the loop will stop when the counter becomes bigger than the input num, and an iterator that adds 1 to the counter each time.
  2. Inside the loop, we find the square root of each number using Math.sqrt(i), then check whether the square root is an integer by testing whether it is the same as itself when it has been rounded down to the nearest integer (this is what Math.floor() does to the number it is passed).
  3. If the square root and the rounded down square root do not equal one another (!==), it means that the square root is not an integer, so we are not interested in it. In such a case, we use the continue statement to skip on to the next loop iteration without recording the number anywhere.
  4. If the square root is an integer, we skip past the if block entirely, so the continue statement is not executed; instead, we concatenate the current i value plus a space at the end of the paragraph content.

while and do…while

for is not the only type of loop available in JavaScript. There are actually many others and, while you don’t need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognize the same features at work in a slightly different way.

First, let’s have a look at the while loop. This loop’s syntax looks like so:

initializer
while (condition) {
  // code to run

  final-expression
}

This works in a very similar way to the for loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run, rather than these two items being included inside the parentheses.
The condition is included inside the parentheses, which are preceded by the while keyword rather than for.

The same three items are still present, and they are still defined in the same order as they are in the for loop.
This is because you must have an initializer defined before you can check whether or not the condition is true.
The final-expression is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the condition is still true.

Let’s have a look again at our cats list example, but rewritten to use a while loop:

 cats    

 myFavoriteCats  "My cats are called "

 i  

 i  catslength 
   i  catslength   
    myFavoriteCats  
    
    myFavoriteCats  
  

  i


consolemyFavoriteCats // "My cats are called Pete, Biggles, and Jasmine."
initializer
do {
  // code to run

  final-expression
} while (condition)

In this case, the initializer again comes first, before the loop starts. The keyword directly precedes the curly braces containing the code to run and the final expression.

 cats    

 myFavoriteCats  "My cats are called "

 i  

 
   i  catslength   
    myFavoriteCats  
    
    myFavoriteCats  
  

  i
  i  catslength

consolemyFavoriteCats // "My cats are called Pete, Biggles, and Jasmine."

Active learning: Launch countdown

In this exercise, we want you to print out a simple launch countdown to the output box, from 10 down to Blastoff.
Specifically, we want you to:

  • Loop from 10 down to 0. We’ve provided you with an initializer — let i = 10;.
  • For each iteration, create a new paragraph and append it to the output <div>, which we’ve selected using const output = document.querySelector('.output');.
    In comments, we’ve provided you with three code lines that need to be used somewhere inside the loop:
    • const para = document.createElement('p'); — creates a new paragraph.
    • output.appendChild(para); — appends the paragraph to the output <div>.
    • para.textContent = — makes the text inside the paragraph equal to whatever you put on the right-hand side, after the equals sign.
  • Different iteration numbers require different text to be put in the paragraph for that iteration (you’ll need a conditional statement and multiple para.textContent = lines):
    • If the number is 10, print «Countdown 10» to the paragraph.
    • If the number is 0, print «Blast off!» to the paragraph.
    • For any other number, print just the number to the paragraph.
  • Remember to include an iterator! However, in this example we are counting down after each iteration, not up, so you don’t want i++ — how do you iterate downwards?

Note: If you start typing the loop (for example (while(i>=0)), the browser might get stuck because you have not yet entered the end condition. So be careful with this. You can start writing your code in a comment to deal with this issue and remove the comment after you finish.

If you make a mistake, you can always reset the example with the «Reset» button.
If you get really stuck, press «Show solution» to see a solution.

Live output
   410px auto

Editable code

  Press Esc to move focus away from the code area (Tab inserts a tab character).

    300px 95%
let output = document.querySelector('.output');
output.innerHTML = '';

// let i = 10;

// const para = document.createElement('p');
// para.textContent = ;
// output.appendChild(para);



      
      

 
   sans-serif


 
   16px


 
   0
   right
   0.7rem
   98%


 
   10px
   #f5f9fa

 textarea  document
 reset  document
 solution  document
 code  textareavalue
 userEntry  textareavalue

  
  textareavalue


reset   
  textareavalue  code
  userEntry  textareavalue
  solutionEntry  jsSolution
  solutionvalue  
  


solution   
   solutionvalue   
    textareavalue  solutionEntry
    solutionvalue  
    
    textareavalue  userEntry
    solutionvalue  
  
  


 jsSolution  

 solutionEntry  jsSolution

textarea updateCode
window updateCode

// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead

textarea    
   ekeyCode   
    e
    
  

   ekeyCode   
    textarea
  


  
   scrollPos  textareascrollTop
   caretPos  textareaselectionStart
   front  textareavalue caretPos
   back  textareavalue
    textareaselectionEnd
    textareavaluelength
  

  textareavalue  front  text  back
  caretPos  textlength
  textareaselectionStart  caretPos
  textareaselectionEnd  caretPos
  textarea
  textareascrollTop  scrollPos




textarea    
  
  
   solutionvalue   
    userEntry  textareavalue
    
    solutionEntry  textareavalue
  

  

Active learning: Filling in a guest list

In this exercise, we want you to take a list of names stored in an array and put them into a guest list. But it’s not quite that easy — we don’t want to let Phil and Lola in because they are greedy and rude, and always eat all the food! We have two lists, one for guests to admit, and one for guests to refuse.

Specifically, we want you to:

  • Write a loop that will iterate through the people array.
  • During each loop iteration, check if the current array item is equal to «Phil» or «Lola» using a conditional statement:
    • If it is, concatenate the array item to the end of the refused paragraph’s textContent, followed by a comma and a space.
    • If it isn’t, concatenate the array item to the end of the admitted paragraph’s textContent, followed by a comma and a space.

We’ve already provided you with:

  • refused.textContent += — the beginnings of a line that will concatenate something at the end of refused.textContent.
  • admitted.textContent += — the beginnings of a line that will concatenate something at the end of admitted.textContent.

Extra bonus question — after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy — there will be a comma at the end of each one.
Can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end?
Have a look at the Useful string methods article for help.

If you make a mistake, you can always reset the example with the «Reset» button.
If you get really stuck, press «Show solution» to see a solution.

Live output
   100px auto
  Admit:
  Refuse:


Editable code

  Press Esc to move focus away from the code area (Tab inserts a tab character).

    400px 95%
const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];

const admitted = document.querySelector('.admitted');
const refused = document.querySelector('.refused');
admitted.textContent = 'Admit: ';
refused.textContent = 'Refuse: ';

// loop starts here

// refused.textContent += ;
// admitted.textContent += ;




      
      

 
   sans-serif


 
   16px


 
   0
   right
   0.7rem
   98%


 
   10px
   #f5f9fa

 textarea  document
 reset  document
 solution  document
 code  textareavalue
 userEntry  textareavalue

  
  textareavalue


reset   
  textareavalue  code
  userEntry  textareavalue
  solutionEntry  jsSolution
  solutionvalue  
  


solution   
   solutionvalue   
    textareavalue  solutionEntry
    solutionvalue  
    
    textareavalue  userEntry
    solutionvalue  
  
  


 jsSolution  

 solutionEntry  jsSolution

textarea updateCode
window updateCode

// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead

textarea    
   ekeyCode   
    e
    
  

   ekeyCode   
    textarea
  


  
   scrollPos  textareascrollTop
   caretPos  textareaselectionStart
   front  textareavalue caretPos
   back  textareavalue
    textareaselectionEnd
    textareavaluelength
  

  textareavalue  front  text  back
  caretPos  textlength
  textareaselectionStart  caretPos
  textareaselectionEnd  caretPos
  textarea
  textareascrollTop  scrollPos




textarea    
  
  
   solutionvalue   
    userEntry  textareavalue
    
    solutionEntry  textareavalue
  

  

Which loop type should you use?

Let’s have a look at them all again.

for (const item of array) {
  // code to run
}
for (initializer; condition; final-expression) {
  // code to run
}
initializer
while (condition) {
  // code to run

  final-expression
}
initializer
do {
  // code to run

  final-expression
} while (condition)

Note: There are other loop types/features too, which are useful in advanced/specialized situations and beyond the scope of this article. If you want to go further with your loop learning, read our advanced Loops and iteration guide.

Дополнительно:  Какая версия Android должна быть установлена на HTC Wildfire S (Black)?

Test your skills!

You’ve reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you’ve retained this information before you move on — see Test your skills: Loops.

Conclusion

This article has revealed to you the basic concepts behind, and different options available when looping code in JavaScript.
You should now be clear on why loops are a good mechanism for dealing with repetitive code and raring to use them in your own examples!

See also

Bash For Loop Syntax

for varname in list;do command1;command2;done

for var in $(cat file1);do command1;command2;done

for variable in server1 server2;do command1;command2;done

15 Practical Bash For Loop Examples in Linux/Unix for Professionals

Also Read: How to Drop/Flush/Clear Cache Memory or RAM in Linux (RedHat/CentOS 7/8)

Example 1: How to Sync Time in multiple servers using Bash For Loop in Linux

If you want to sync time in multiple servers using bash for loop in Linux then you can use below loop. In this example, we have provided the IP of all Servers in server.txt and then going to every server using for loop and setting the time to 16:08:00 using date command as shown below.

[root@localhost ~]# 

Please note that here I have already enabled passwordless authentication between Servers to avoid any password prompt. So do not be surprise if you run any of the commands given in this article and it ask you to provide the authentication password. To Know more about setting up Passwordless authentication, you can check Passwordless ssh login using ssh keygen in 6 Easy Steps.

Example 2: How to Check next 5 CPU Load Average using Bash For Loop in Linux

If you want to check next 5 CPU Load Average using bash for loop in Linux then you need to loop through each of the sequence from 1 to 5 and display the load average using cat /proc/loadavg for every sequence as shown below.

[root@localhost ~]# for i in $(seq 5);do cat /proc/loadavg;sleep 3;done
0.00 0.01 0.05 2/141 25158
0.00 0.01 0.05 2/141 25160
0.00 0.01 0.05 2/141 25162
0.00 0.01 0.05 2/141 25164
0.00 0.01 0.05 2/141 25166

Example 3: How to check the processes using maximum swap memory in Linux

If you want to check the processes using maximum swap memory in linux then you can use below bash for loop. In this example, we are using awk and sort tool with bash for loop to check the processes using swap memory as shown below.

[root@localhost ~]# 

Example 4: How to convert all rows into columns based on Colon(:) separator

You can also use bash for loop to convert all rows into columns based on Colon Separator(:) as shown below. In this example, we are creating a file testfile.txt and converting its rows to columns using cut and paste command with for loop. Firstly we need to create a file testfile.txt using vi testfile.txt command.

[root@localhost ~]# 

Then we need to run below bash for loop from i=1 to i<=3 to convert the rows into columns.

[root@localhost ~]# 
Hi      This     hello
you      is      world
there CYBERITHUB example

Example 5: How to convert all rows into columns based on Comma(,) field separator

Like above example, you can also use bash for loop to convert all rows into columns based on Comma(,) as shown below. In this example, we are creating a file testfile.txt and converting its rows to columns using cut, column and paste command with bash for loop as specified below. First let’s create the file testfile.txt using vi editor.

[root@localhost ~]# 

Then we need to run below bash for loop from i=1 to i<=3 to convert the rows into columns.

[root@localhost ~]# 
Hi       This     hello
you       is      world
there CYBERITHUB example

Example 6: How to Check the OS Version of Multiple Servers using bash for loop in Linux

If you want to check the OS Version of multiple servers using bash for loop in one line then you need to run below command. In this example, we are looping through 14.188.134.26 and 14.188.21.242 servers and running cat /etc/redhat-release command in each Server as specified below.

[root@localhost ~]# 
********OS Version of 14.188.134.26********
CentOS Linux release 7.8.2003 (Core)
********OS Version of 14.188.21.242********
CentOS Linux release 7.8.2003 (Core)

Example 7: How to Check the Memory Stats using bash for loop in Linux

If you want to check the memory stats of multiple servers in one line then you can use below bash for loop. In this example we are checking the memory stats of Servers 14.188.134.26 and 14.188.21.242 by looping through each of the server and running free -g command as shown below.

[root@localhost ~]# 
********Memory Stats of 14.188.134.26********

********Memory Stats of 14.188.21.242********

Example 8: How to Find the Private IP of AWS EC2 Instance using bash for loop

[root@localhost ~]# 
********Private IP of 14.188.134.26********
inet 172.31.14.87/20 brd 172.31.15.255 scope global dynamic eth0
********Private IP of 14.188.21.242********
inet 172.31.14.87/20 brd 172.31.15.255 scope global dynamic eth0

Example 9: How to Create a File in Multiple Servers using Bash For Loop in Linux

You can create a file in multiple servers using bash for loop in a single line as shown below. In this example, we are creating a file test.txt in server1 and server2 by looping through each server and running touch test.txt command as specified below.

[root@localhost ~]# for i in server1 server2;do ssh -q $i "touch test.txt;sleep 2";done

Example 10: How to start an application in multiple Linux Servers

If you want to start an application in a bunch of servers without manually login to each servers then you can use below bash for loop. In this example, we are starting an application /opt/app/start.sh > /dev/null in server1 and server2 and then checking the status using /opt/app/status.sh as shown below.

[root@localhost ~]# 

Example 11: How to check disk space of multiple Linux Servers

If you want to check the disk space is multiple Linux servers then you can use below bash for loop. In this example we are looping through all the servers of Servers.list and checking the disk space of /opt/backup and /opt/log using df -h /opt/backup /opt/log command.

[root@localhost ~]# for i in $(cat Servers.list);do ssh $i 'df -h /opt/backup /opt/log';done

Example 12: How to Check Kernel Version of Multiple Linux Servers

If you want to check the Kernel Version of Multiple Linux Servers then you need to use below for loop. In this example we are checking the Kernel version of 14.188.134.26 and 14.188.21.242 servers using uname -r command with for loop as shown below.

[root@localhost ~]# 
********Kernel Version of 14.188.134.26********

********Kernel Version of 14.188.21.242********

Example 13: How to Find the total number of CPUs in Multiple Servers using bash for loop in Linux

If you want to find the total number of CPU cores in multiple servers then you can use below bash for loop. In this example, we are looping through Server 14.188.134.26.54 and 14.188.21.242 and running lscpu command in each of the server to find the total number of cores.

[root@localhost ~]# 
********Number of CPUs in 14.188.134.26********

********Number of CPUs in 14.188.21.242********

Example 14: How to Check SELinux Status in Multiple Servers using bash for loop in Linux

You can also use bash for loop to check the SELinux status in multiple servers. In this example we are checking the status of selinux by looping through 14.188.134.26 and 14.188.21.242 servers and running sestatus command as shown below.

[root@localhost ~]# 
********SELinux Status in 14.188.134.26********
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Max kernel policy version: 31
********SELinux Status in 14.188.21.242********
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Max kernel policy version: 31

Example 15: How to Check the Service Status in Multiple Servers using bash for loop in Linux

You can also use bash for loop to check the service status in multiple servers. In this example we are checking the status of iptables service by looping through 14.188.134.26 and 14.188.21.242 servers and running systemctl  status iptables command as shown below.

[root@localhost ~]# 
********IPTABLES Status in 14.188.134.26********
● iptables.service - IPv4 firewall with iptables
Loaded: loaded (/usr/lib/systemd/system/iptables.service; enabled; vendor preset: disabled)
Active: active (exited) since Sat 2020-09-05 20:38:20 UTC; 1h 0min ago
Process: 612 ExecStart=/usr/libexec/iptables/iptables.init start (code=exited, status=0/SUCCESS)
Main PID: 612 (code=exited, status=0/SUCCESS)








********IPTABLES Status in 14.188.21.242********
● iptables.service - IPv4 firewall with iptables
Loaded: loaded (/usr/lib/systemd/system/iptables.service; enabled; vendor preset: disabled)
Active: active (exited) since Sat 2020-09-05 20:38:20 UTC; 1h 0min ago
Process: 612 ExecStart=/usr/libexec/iptables/iptables.init start (code=exited, status=0/SUCCESS)
Main PID: 612 (code=exited, status=0/SUCCESS)







10 Useful iproute2 tools examples to Manage Network Connections in Linux

6 Popular Methods to List All Running Services Under Systemd in Linux

33 Practical Examples of ulimit command in Linux/Unix for Professionals

Install Node.js in 6 Easy Steps on Ubuntu 18.04

How to Install NVM for Node.js on Ubuntu 18.04

How to Limit CPU Limit of a Process Using CPULimit in Linux (RHEL/CentOS 7/8)

How to Install Rust Programming Language in Linux Using 6 Best Steps

Bash For Loop Examples to Check Processes using Swap Memory in Linux

Оцените статью
Master Hi-technology
Добавить комментарий