Linux bash increment variable

Как увеличивать и уменьшать переменную в Bash (Counter)

Одна из наиболее распространенных арифметических операций при написании сценариев Bash — это увеличение и уменьшение переменных. Это чаще всего используется в циклах в качестве счетчика, но может встречаться и в другом месте сценария.

Увеличение и уменьшение означает добавление или вычитание значения (обычно 1 ), соответственно, из значения числовой переменной. Арифметическое раскрытие может быть выполнено с использованием двойных скобок ((. )) и $((. )) или с помощью встроенной команды let .

В Bash есть несколько способов увеличения / уменьшения переменной. Эта статья объясняет некоторые из них.

Использование операторов + и —

Самый простой способ увеличить / уменьшить переменную — использовать операторы + и — .

Этот метод позволяет вам увеличивать / уменьшать переменную на любое значение, которое вы хотите.

Вот пример увеличения переменной в цикле until :

Операторы += и -=

В дополнение к основным операторам, описанным выше, bash также предоставляет операторы присваивания += и -= . Эти операторы используются для увеличения / уменьшения значения левого операнда на значение, указанное после оператора.

В дальнейшем в while цикла, мы декремент значения i переменный на 5 .

Использование операторов ++ и —

Операторы ++ и — увеличивают и уменьшают соответственно его операнд на 1 и возвращают значение.

Операторы могут использоваться до или после операнда. Они также известны как:

  • приращение префикса: ++i
  • префиксный декремент: —i
  • постфиксное приращение: i++
  • постфиксный декремент: i—

Операторы префикса сначала увеличивают / уменьшают операторы на 1 а затем возвращают новое значение операторов. С другой стороны, постфиксные операторы возвращают значение операторов до того, как оно было увеличено / уменьшено.

Если вы хотите только увеличивать / уменьшать переменную, то нет никакой разницы, используете ли вы префиксный или постфиксный оператор. Это имеет значение только в том случае, если результат операторов используется в какой-либо другой операции или присваивается другой переменной.

Следующие примеры демонстрируют, как работает оператор ++ когда он используется до и после его операнта:

Ниже приведен пример использования постфиксного инкрементора в сценарии bash:

Недостатком использования этих операторов является то, что переменная может увеличиваться или уменьшаться только на 1 .

Выводы

Увеличение и уменьшение переменных в Bash можно выполнять разными способами. Какой бы метод вы ни использовали, результат будет одинаковым.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

4 practical examples with bash increment variable

Table of Contents

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.

  • 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
Читайте также:  Arch linux alarm clock

Output from this script:

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:

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.

Output from this script:

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:

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

Output from this script:

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.

Output from this script:

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

Читайте также:  Сдвинуть экран windows 10

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.

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

Thank You for your support!!

Источник

Last Updated: January 2nd, 2020 by Hitesh J in Guides, Linux

When writing Bash scripts, one of the most common arithmetic operations is Incrementing and Decrementing variables.

Generally, it is used in a loop as a counter. Sometimes you will need to write while loop where you need to define increment or decrement variables for the normal function of loops.

There are several ways to increment and decrement a variable in Bash.

In this tutorial, we will show you how to increment and decrement a variable in Bash.

Using + and – Operators

You can use increment operator (+) increase the value of the variable by one and decrement operator (-) decrease the value of the variable by one in Bash.

The basic syntax of increment operator (+) and decrement operator (-) are shown below:

Increment Operator

Decrement Operator

Let’s see an example of incrementing a variable by one in until loop.

Add the following code:

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

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

count: 0
count: 1
count: 2
count: 3
count: 4

In the above program, the value of count is incremented one by one from 1 up to 4 using + operator.

You should see all the commands in the following screen:

Next, see an example of decrementing a variable by one in until loop.

Add the following code:

#!/bin/bash
count=5
until [ $count -le 0 ]
do
echo count: $count
((count=count-1))
done

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

count: 5
count: 4
count: 3
count: 2
count: 1

In the above program, the value of count is decremented one by one from 5 up to 0 using operator.

You should see all the commands in the following screen:

Using += and -= Operators

Bash also provides the assignment operators += and -= to increment and decrement the value of the left operand with the value specified after the operator.

The basic syntax of increment (+=) and decrement (-=) operators are shown below:

Increment (+=) Operators

Decrement (-=) Operators

Let’s see an example of incrementing the value of the variable count by 3.

Add the following code:

#!/bin/bash
count=0
while [ $count -le 12 ]
do
echo Number: $count
let «count+=3»
done

Save and close the file when you are finished. Then, run the script with the following command:

You should see the following output:

Number: 0
Number: 3
Number: 6
Number: 9
Number: 12

You should see the output of all the commands in the following screen:

Let’s see another example of decrementing the value of the variable count by 4.

Add the following code:

#!/bin/bash
count=40
while [ $count -ge 4 ]
do
echo Number: $count
let «count-=4»
done

Save and close the file when you are finished. Then, run the script with the following command:

You should see the following output:

Number: 40
Number: 36
Number: 32
Number: 28
Number: 24
Number: 20
Number: 16
Number: 12
Number: 8
Number: 4

You should see the output of all the commands in the following screen:

Using the ++ and — Operators

Bash has two special unary operators increment (++) and decrement (–) operators. Increment (++) operator increases the value of a variable by 1 and decrement (–) operator decreases the value of a variable by 1, and return the value.

The basic syntax of the increment (++) and decrement (–) operators are shown below:

Increment (++) Operator

Decrement (–) Operator

Increment and Decrement operators are of two types:

  • Prefix increment and decrement operator : ++i and –i
  • Postfix increment and decrement operator : i++ and i–

In prefix operator (++i/–i), the value of i is incremented/decremented by 1 then, it returns the value.

In postfix operator (i++/i–), the original value of i is returned first then, i is incremented by 1.

Let’s see an example of how prefix (++i) increment operator works.

Add the following code:

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

In the above example, the current value of a is assigned to b then a is incremented.

You should see all the commands in the following screen:

Next, let’s see an another example of how postfix (++i) increment operator works.

Add the following code:

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

In the above example, the current value of a is incremented by 1. The new value of a is then assigned to b.

You should see all the commands in the following screen:

You can also use the postfix increment operator in a bash script.

To do so, let’s create a new bash script as shown below:

Add the following code:

#!/bin/bash
a=0
while true; do
if [[ «$a» -gt 5 ]]; then
exit 1
fi
echo a: $a
((a++))
done

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

You should see all the commands in the following screen:

If you want to use the postfix decrement operator in a bash script, let’s create a new bash script as shown below:

Add the following code:

#!/bin/bash
a=5
while true; do
if [[ «$a» -le 0 ]]; then
exit 1
fi
echo a: $a
((a—))
done

Save and close the file when you are finished. Then, run the script as shown below:

You should see the following output:

You should see all the commands in the following screen:

Conclusion

In the above tutorial, we learned how to use increment and decrement operators in Bash script in several ways. We hope you’ve learned how to use these operators in Bash as per your requirements and needs.

Feel free to comment below if you have any questions.

Источник

Читайте также:  Не срабатывает запуск windows
Оцените статью