Bash for Loop Examples.

Examples of Bash for Loop

  1. Bhawani Singh
    In this article we are going to share some loop examples. There are two types of loops, one contain the “in” and second is without the keywords. When you will read the whole article so you will understand the uses and syntax of loop.

    1). Bash for Loop by using “in”
    Syntax:
    In above example “for”, “in”, “do”, “done” are keywords and “list” is for list the values.
    Suppose if you have a variable in the list which can hold several words separated by spaces. In case the list is missing in given statement, then it has the parameter which was passed into the shell.

    Here varname define any Bash variable name.

    In order to execute the statement which is enclosed in the body? For the instance the list is containing 5 values so the command will execute 5 times, once for each in the list and value will be stored in varname.

    2). Bash for Loop using C like syntax
    This loop is very similar to the “for” loop in C programming language, where it contains three expressions (initialization, condition and updation).
    The first step is "initialization" which is used to start the loop from, "condition" means it will execute as given condition and updation define increment / decrement of value.

    Here we are going to share some examples that show how to use bash for loops in various ways.
    I. Use static values for the list using "in"
    Suppose we have a list of values as Jun, Feb, Mar, Apr and May. In the loop we put these values after the keyword “in”, just see the below example.
    Caution:
    Avoid comma in separate values as Jun, Feb, Mar, Apr, May. If you allow it so it counts as a part of value. When you consider comma in given values, so you will get some different result. See in the given example.
    Caution:
    Don’t use double quote in the given values like “Jun Feb Mar Apr May”. When you use it as so it will consider a single value, not count as a 5 different value. Now just see below example.
    II. List Variable after “in” keyword
    In above we have shared only static, but now we will provide variable instead of value directly. Here we are going to share the uses of variable in for loop after using “in” keyword. See the below example.
    Caution:
    Suppose if you use the double quote for the variable, then the value will be count as the single value. Just see the below example.
    III. Without specifying the list; get it from the positional parameters
    When you don’t specify the list, so it will take positional parameters and get the following result.
    Caution:
    Always be careful to use this way. You don’t need to include the keyword “in” in for loop. If you do not use this keyword “in” without any values, so what you will get just the see the below.