For loop command in linux

How to make a for loop in command line?

AFAIK semicolon in bash scripts makes shell execute current command synchronously and then go to the next one. Pressing enter does literally the same except it doesn’t allow you to enter the following command, flushing the buffer immediately. So why shell can’t interpret the following line

for i in `seq 1 10`; do; echo $i; done 

3 Answers 3

The syntax of a for loop from the bash manual page is

for name [ [ in [ word . ] ] ; ] do list ; done 

The semicolons may be replaced with carriage returns, as noted elsewhere in the bash manual page: «A sequence of one or more newlines may appear in a list instead of a semicolon to delimit commands.»

However, the reverse is not true; you cannot arbitrarily replace newlines with semicolons. Your multiline script can be converted to a single line as long as you observe the above syntax rules and do not insert an extra semicolon after the do :

for i in `seq 1 10`; do echo $i; done 

@jake, this also says you must remove the semicolon after do . In addition, this answer explains why you must remove the semicolon after `do’.

The semicolon after do is an error and should not be there.

The following works correctly:

for i in `seq 1 10`; do echo $i; done 
> for name in ; do echo $name;done Regular Italic Bold-Italic 

The element is called brace expansion. Basically your shell expands this element and uses each produced entry into the for loop (see here for more info about brace expansion). If you don’t use <> , the shell will understand 1,2,3 as a single element, and would get through in the loop only once, producing

❯ for name in Regular,Italic,Bold-Italic; do echo $name;done Regular,Italic,Bold-Italic 

which is not what you are probably expecting.

Alternatively, you can also use brace expansion to create a sequence using the following notation

❯ for i in ; do echo $i; done 1 2 3 4 5 

It is worth to mention that you can create different strings with a sequence pattern using brace expansion and use it into the for loop, as shown here:

❯ for i in ABC; do echo $i; done A1BC A2BC A3BC A4BC A5BC 

Источник

How to Use Bash For Loop with Examples in Linux

In programming languages, Loops are essential components and are used when you want to repeat code over and over again until a specified condition is met.

In Bash scripting, loops play much the same role and are used to automate repetitive tasks just like in programming languages.

In Bash scripting, there are 3 types of loops: for loop, while loop, and until loop. The three are used to iterate over a list of values and perform a given set of commands.

Читайте также:  Create partition linux windows

In this guide, we will focus on the Bash For Loop in Linux.

Bash For Loop Syntax

As mentioned earlier, the for loop iterates over a range of values and executes a set of Linux commands.

For loop takes the following syntax:

for variable_name in value1 value2 value3 .. n do command1 command2 commandn done

Let us now check a few example usages of the bash for loop.

Bash For Loop Example

In its simplest form, the for loop takes the following basic format. In this example, the variable n iterates over a group of numerical values enclosed in curly braces and prints out their values to stdout.

Bash For Loop Example

Bash For Loop with Ranges

In the previous examples, we explicitly listed the values to be iterated by the for loop, which works just fine. However, you can only imagine how cumbersome and time-consuming a task it would be if you were to iterate over, for example, a hundred values. This would compel you to type all the values from 1 to 100.

To address this issue, specify a range. To do so, specify the number to start and stop separated by two periods.

In this example, 1 is the first value whilst 7 is the last value in the range.

#!/bin/bash for n in ; do echo $n done

Once the shell script is executed, all the values in the range are listed, similar to what we had in simple loops.

Bash For Loop with Ranges Example

Additionally, we can include a value at the end of the range that is going to cause the for loop to iterate through the values in incremental steps.

The following bash script prints the values between 1 and 7 with 2 incremental steps between the values starting from the first value.

#!/bin/bash for n in ; do echo $n done

Bash For Loop Incremented Values

From the above example, you can see that the loop incremented the values inside the curly braces by 2 values.

Bash For Loops with Arrays

You can also easily iterate through values defined in an array using a for Loop. In the following example, the for loop iterates through all the values inside the fruits array and prints them to stdout.

#!/bin/bash fruits=("blueberry" "peach" "mango" "pineapple" "papaya") for n in $; do echo $n done

Bash For Loop Array Example

The @ operator accesses or targets all the elements. This makes it possible to iterate over all the elements one by one.

In addition, you can access a single element by specifying its position within the array.

For example to access the “mango” element, replace the @ operator with the position of the element in the array (the first element starts at 0, so in this case, “mango” will be denoted by 2).

This is what the for loop looks like.

#!/bin/bash fruits=("blueberry" "peach" "mango" "pineapple" "papaya") for n in $; do echo $n done

Bash For Loops with Array Elements

Bash C Style For Loop

You can use variables inside loops to iterate over a range of elements. This is where C-styled for loops come in. The following example illustrates a C-style for loop that prints out a list of numerical values from 1 to 7.

Читайте также:  Xinput calibrator astra linux

Bash C-styled For Loops Example

Bash C-styled For Loops With Conditional Statements

You can include conditional statements inside C-styled for loops. In the following example, we have included an if-else statement that checks and prints out even and odd numbers between 1 and 7.

Bash C-styled For Loops Conditional Statements Example

Use the ‘Continue’ statement with Bash For Loop

The ‘continue‘ statement is a built-in command that controls how a script runs. Apart from bash scripting, it is also used in programming languages such as Python and Java.

The continue statement halts the current iteration inside a loop when a specific condition is met, and then resumes the iteration.

Consider the for loop shown below.

#!/bin/bash for n in do if [[ $n -eq '6' ]] then echo "Target $n has been reached" continue fi echo $n done

Bash For Loop Continue Statement Example

This is what the code does:

  • Line 2: Marks the beginning of the for loop and iterate the variable n from 1 to 10.
  • Line 4: Checks the value of n and if the variable is equal to 6, the script echoes a message to stdout and restarts the loop at the next iteration in line 2.
  • Line 9: Prints the values to the screen only if the condition in line 4 is false.

The following is the expected output after running the script.

Bash For Loop Continue Statement Output

Use the ‘break’ statement with Bash For Loop

The ‘break’ statement, as the name suggests, halts or ends the iteration when a condition is met.

Consider the For loop below.

#!/bin/bash for n in do if [[ $n -eq '6' ]] then echo "Target $n has been reached" break fi echo $n done echo "All done"

Bash For Loop Break Statement

This is what the code does:

  • Line 2: Marks the beginning of the for loop and iterate the variable n from 1 to 10.
  • Line 4: Checks the value of n and if the variable is equal to 6, the script echoes a message to stdout and halts the iteration.
  • Line 9: Prints the numbers to the screen only if the condition in line 4 is false.

From the output, you can see that the loop stops once the variable meets the condition of the loop.

Bash For Loop Break Statement Output

Conclusion

That was a tutorial about Bash For loops. We hope you found this insightful. Feel free to weigh in with your feedback.

Источник

How do I write a ‘for’ loop in Bash?

It’s worth a mention that the range specified here is inclusive. By that, I mean you will see the entire range (1 to 10) printed to the console.

I prefer this solution since it does not use a seq so it does not generate a weird string containing a sequence of all the numbers, but it just loops efficiently over an integer.

The Bash for consists on a variable (the iterator) and a list of words where the iterator will, well, iterate.

So, if you have a limited list of words, just put them in the following syntax:

for w in word1 word2 word3 do doSomething($w) done 

Probably you want to iterate along some numbers, so you can use the seq command to generate a list of numbers for you: (from 1 to 100 for example)

Читайте также:  Федорчук доступный unix linux freebsd dragonflybsd netbsd openbsd

and use it in the for loop:

for n in $(seq 1 100) do doSomething($n) done 

Note the $(. ) syntax. It’s a Bash behaviour, and it allows you to pass the output from one command (in our case from seq ) to another (the for ).

This is really useful when you have to iterate over all directories in some path, for example:

for d in $(find $somepath -type d) do doSomething($d) done 

The possibilities are infinite to generate the lists.

Good answer, but you might want to include the for ((i=0; i

Bash 3.0+ can use this syntax:

. which avoids spawning an external program to expand the sequence (such as seq 1 10 ).

Of course, this has the same problem as the for(()) solution, being tied to Bash and even a particular version (if this matters to you).

Try the Bash built-in help:

Output

for: for NAME [in WORDS . ;] do COMMANDS; done The `for' loop executes a sequence of commands for each member in a list of items. If `in WORDS . ;' is not present, then `in "$@"' is assumed. For each element in WORDS, NAME is set to that element, and the COMMANDS are executed. for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done Equivalent to (( EXP1 )) while (( EXP2 )); do COMMANDS (( EXP3 )) done EXP1, EXP2, and EXP3 are arithmetic expressions. If any expression is omitted, it behaves as if it evaluates to 1. 
#! /bin/bash function do_something < echo value=$> MAX=4 for (( i=0; i > 

Here’s an example that can also work in older shells, while still being efficient for large counts:

But good luck doing useful things inside of awk : How do I use shell variables in an awk script?

I didn’t notice it before, but a similar syntax is shown in one of the earlier answers. The unique thing here is the use of curly-braces instead of the typical do / done pair.

I commonly like to use a slight variant on the standard for loop. I often use this to run a command on a series of remote hosts. I take advantage of Bash’s brace expansion to create for loops that allow me to create non-numerical for loops.

I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:

% for host in ,backend>.mycompany.com do ssh $host "echo -n $host; uptime" done 

I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. prepost results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z, etc.). However, the double period syntax is a new feature of Bash 3.0; earlier versions will not support this.

Источник

Оцените статью
Adblock
detector