Linux bash increment variable

How to Increment and Decrement Variable in Bash?

Increment or decrement variable is a popularly used arithmetic operation in many programming languages. The increment adds a number, and the decrement subtracts a number programmatically. The bash script allows the incrementing or decrementing of the variables, mostly used with the loops as a counter, but it can be used within the script to increase or decrease the variable value.

This guide will explain different methods for incrementing and decrementing variables in bash with the following timeline:

  • How to Increment or Decrement a Variable in Bash?
    • Syntax for Increment and Decrement Variable
    • Example 1: Increment the Variable in Bash
    • Example 2: Increment the Variable in Bash Using While Loop
    • Example 3: Increment the Variable in Bash Using Until Loop
    • Example 1: Decrement the Variable in Bash
    • Example 2: Decrement the Variable in Bash Using While Loop
    • Example 3: Decrement the Variable in Bash Using Until Loop
    • Example 4: Decrement the Variable by 3 in Bash Using Until Loop

    How to Increment or Decrement a Variable in Bash?

    Several bash syntaxes and operators are used to increment and decrement variables. Let’s check the syntax and operators with the help of examples.

    Syntax for Increment and Decrement Variable

    The increment or decrement is done using the three formats:

    • Double brackets (())
    • Declaring a variable with double brackets $(())
    • Using the let “”

    For instance, to increment the variable var, the below syntaxes are used:

    $ ((var=var+1)) ((var=var+1)) let "var=var+1"

    Similarly, to decrement the variable var, the following syntaxes can be executed:

    $ ((var=var-1)) ((var=var-1)) let "var=var-1"

    Type of Increment and Decrement Operators in Bash

    The following operators are used for incrementing or decrementing the variables in bash:

    + operator – operator var=var+1 var=var-1
    ++ operator — operator var++ ++var var– –var
    += operator +- operator var+=1 var-=1

    How to Use Bash to Increment or Decrement Variables?

    This section will discuss several methods to decrement or increment variables.

    Example 1: Increment the Variable in Bash

    We can increment the variables in Bash by declaring it within curly brackets. This method is commonly used in Linux to increment the variable. For instance, to increment the variable by 1, use the below increment code:

    #!/bin/bash var=5 var=$((var+1)) echo "The incremented values is: $var"

    To check the above bash script output, use this command:

    The output displays that the variable var=5 is incremented to 6.

    The variable in bash can be incremented using the double curly brackets only. To increment the variable var by 1, use this code:

    #!/bin/bash var=10 ((var=var+1)) echo "The incremented values is: $var"

    To execute the above increment code, run this command:

    $ ~/increment.sh

    The variable var=10 is added by 1 is shown in the output.

    The let command is also used to increment in the Bash script. To increment the variable var using the let syntax, execute this code:

    #!/bin/bash var=15 let "var=var+1" echo "The incremented values is: $var"

    Run the above code with this command:

    The variable is incremented to 16 from 15.

    Example 2: Increment the Variable in Bash Using While Loop

    The loops automate the tasks in the bash script. For instance, to increment the variable using the while loop, execute this bash script:

    For running the bash script, use:

    The output shows that 1 is added to the variable every time the loop executes.

    Example 3: Increment the Variable in Bash Using Until Loop

    The until the loop can also be used to increment a variable. The until loop increments the variable by 1 every time the loop runs and terminates the loop at the maximum set point, as performed below:

    #!/bin/bash i=0 until [ $i -gt 5 ] do echo $i i=$((i+1)) done

    To run the bash script, execute:

    The variable is incremented by 1 from 0 to 5.

    How to Decrement a Variable in Bash?

    As discussed above, we can decrement the bash variable using the three operators –, -+ and -.

    Example 1: Decrement the Variable in Bash

    To decrement the variable by 1, use this below declaring variable bash script:

    #!/bin/bash var=5 var=$((var-1)) echo "The decremented value is: $var"

    Run the decrement bash script code to get the output:

    The variable var=5 is decremented to 4.

    The curly braces syntax can also be used to decrement a variable. For decrementing a variable var=10 by 1, use:

    #!/bin/bash var=10 ((var=var-1)) echo "The decremented value is: $var"

    The decrement bash script code can be executed using:

    The variable var=10 is decreased by 1 to 9.

    The let syntax is used to decrement a variable in bash using this script:

    #!/bin/bash var=15 let "var=var-1" echo "The decremented value is: $var"

    To check the decrement bash script output, run this command:

    The variable is decremented by 1.

    Example 2: Decrement the Variable in Bash Using While Loop

    The below while loop is used to decrement the variable by 1 every tie the loop runs:

    #!/bin/bash i=5 while(($i>0)) do echo $i ((i--)) done

    Run the while loop bash script, running this command in the terminal:

    Example 3: Decrement the Variable in Bash Using Until Loop

    The until is used to decrement a variable for each loop execution, such as the below code will decrement the variable i by 1:

    #!/bin/bash i=5 until [ $i -lt 1 ] do echo $i i=$((i-1)) done

    To get the output for the above script, use:

    The script is decremented by 1 for every loop execution.

    Example 4: Decrement the Variable by 3 in Bash Using Until Loop

    Let’s decrement a loop using the let syntax with the below script, which will decrement the loop by 3 for every time the loop executes:

    #!/bin/bash i=12 while [ $i -ge 3 ] do echo $i let "i-=1" done

    To run the decrement bash script, execute:

    The output is decremented by 3 for every loop execution.

    This guide has explained with examples that how can we increment and decrement variables in Bash.

    Conclusion

    Three different Linux operators and syntaxes are used to increment or decrement in bash. The syntaxes used for incrementing or decrementing a variable are curly brackets (()), declaring a variable within curly brackets $(()), and using the let keyword in the bash script. Moreover, three operators, +, ++, and += are used to increment, and -, –, and -= are utilized to decrement a variable using the bash script. So, this blog has covered in detail how can we increment and decrement variables in Bash.

    Источник

    4 practical examples with bash increment variable

    How to increment variable in bash shell script? How to add 1 to a variable for every for loop? How to increment counter in bash? How to perform bash variable plus 1?

    In this tutorial we will cover these questions. In my previous article we learned about concatenating string which partially covered similar topic of incrementing a variable. Now let’s learn about adding values and incrementing variables in shell scripts when working with loop.

    Increment variable with for loop

    Example-1:

    In this section we will execute a for loop which will iterate based on variable value. The value of this variable will be incremented up to a defined threshold.

    #!/bin/bash for (( i=0; i 5; i++ )); do echo $i done
    • We have defined an initial value for i=0 so the loop will start from 0 , you can change it to any other value from where you wish to start the loop
    • Then the second condition is the threshold where we define the maximum value till the point where the loop should execute. In our case the loop shall run until i is less than or equal to 5 but you may choose any other conditional operator based on your requirement.
    • The third condition is where we increment the value of i variable by plus 1

    4 practical examples with bash increment variable

    Example-2:

    In this example also we will use for loop but now we don’t have a list of numbers to iterate over, instead I have a list of hosts. I want to perform some action with individual hosts but I also don’t want to loop run longer than 3 seconds so I will introduce a timeout.

    So here our timeout variable will be incremented with every loop, and once the timeout value is equal to 3 then the loop will break:

    #!/bin/bash declare -a hosts="ab cd ef gh ij" timeout=1 for host in $@]>; do echo $host if [[ $timeout -eq 3 ]];then echo "timed out" break fi sleep 1  timeout=$((timeout+1)) done

    Here we are incrementing our variable by adding 1 at then end of each loop using timeout=$((timeout+1)) , we could have also used ((timeout++)) which will also increment the timeout variable by one.

    But I prefer the first one because I have more control there, if I have a requirement to increment the variable by any other value such as 5 then we can just update the code to timeout=$((timeout+5))

    Alternatively we can also use ((timeout=timeout+1)) which can also give us an option to add a custom value for increment. So now the timeout variable will be incremented by 5 in every loop.

    4 practical examples with bash increment variable

    Increment variable by plus 1 with while loop

    Example-1:

    Let us now take some examples with while loop. You may have a situation to update a file’s content at some respective line so we can read a file line by line using while loop. In the same script we can add a variable which will count the line number and based on this line number variable we can perform inline operation.

    For example, I want to add » ipv6_disable=1 » in the line with GRUB_CMDLINE_LINUX variable on /etc/sysconfig/grub file. Now this entry has to be appended as a last entry of this line.

    • we will use a while loop to read through the file
    • capture line number into LINE variable
    • based on the line number from LINE we will use sed to perform our operation

    Below is my sample script with all the comments to help you understand the script:

    4 practical examples with bash increment variable

    So we have used the code to increment our line number as used with for loop earlier LINE=$((LINE+1)) . This is the only part which does the magic. You always have to remember two things when using such variable for incrementing

    1. You must initialize an empty variable first as I did by defining LINE=1 as the starting of the script
    2. The initialization must be done before starting the loop, as if you define it inside the loop then the initial value will change every time the variable is incremented which will not give proper results

    4 practical examples with bash increment variable

    So the script is working as expected, it checks for duplicate entries and appends ipv6_disable=1 to disable IPv6 by using LINE to get the line number.

    Check for success and failed scenario by incrementing counter

    Now in all the above example we utilised incremental variable to perform certain task by adding 1 to the variable. Now we will increment counter just to determine the status of command execution and later use that to conclude our execution.

    In this script we check for connectivity of target host. To validate the same I have added a » failed » variable and if the ping test fails then I increment the counter value. Once the ping test is complete then I will check if » failed » variable’s value is more than what we have initialized i.e. 0 and then accordingly we inform the user.

    4 practical examples with bash increment variable

    ~]# ./check_hosts.sh One or more hosts have failed connectivity test

    Now if your requirement is also to have the list of failed hosts then you can use += operator to concatenate strings in a variable.

    Different methods to perform incremental operation in bash

    Here there is a consolidated list of methods which you can choose based on your shell and environment to increment a variable. In the above script where I have used ((failed++)) or LINE=$(($LINE+1)) , just replace this with any of the methods from the below table.

    Number Incremental Variable
    1 var=$((var+1))
    2 var=$((var++))
    3 ((var=var+1))
    4 ((var+=1))
    5 ((var++))
    6 ((++var))
    7 let «var=var+1»
    8 let «var+=1»
    9 let «var++»
    10 let var=var+1
    11 let var+=1
    12 let var++
    13 declare -var var; var=var+1
    14 declare -var var; var+=1
    15 var=$(expr $var + 1)
    16 var=`expr $var + 1`

    Conclusion

    In this tutorial we learned about different incremental operators available in bash shell programming. You have to take care of certain things which I have highlighted multiple places in this article, such as position of the incremental variable, declare the var as integer, exiting the loop properly etc.

    Lastly I hope the steps from the article was helpful. So, let me know your suggestions and feedback using the comment section.

    Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

    If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

    Buy GoLinuxCloud a Coffee

    For any other feedbacks or questions you can either use the comments section or contact me form.

    Thank You for your support!!

    Источник

    Читайте также:  Arduino ide linux libraries
Оцените статью
Adblock
detector