Bash integer counter just like in C

In almost all high level languages you can do something similar to x++ to increment an integer counter.

x=3
x++
print $x

Output would be “4″ minus the quotes. You can also do it by repeating the variable and adding one.

x=3
x=x+1
print $x

This is the same thing as x++. In bash, you don’t have a ++ incrementer, but you can still make your own integer counter using back-ticks and expr. You just set the value of count to the output of expr.

pie

Easy as pie.

#!/bin/bash
count=0
count=`expr ${count} + 1`

Here’s an example. Suppose you want to use the rpm command to install/remove something, but you don’t know if it’s running already? You can make a timer that increments and go into a deeper and deeper sleep the longer you’re waiting for rpm to go away from the process list.

#!/bin/bash
inception=1

while [ "`pgrep rpm | wc -l`" != 0 ]; do
  sleep ${inception}
  inception=`expr ${inception} + 1`
  echo "Sleeping ${inception} seconds..."
done
rpm -Uvh awesome-1.0.x86_64.rpm
Posted by admica   @   6 August 2010

Related Posts

Like this post? Share it!

Digg Twitter StumbleUpon Delicious Technorati Facebook RSS

1 Comments

Comments
Oct 25, 2010
11:48 am
#1 noname :

You can also use arithmetic expansion:

inception=0

sleep $((inception += 1))

see http://tldp.org/LDP/abs/html/arithexp.html

Leave a Comment

Name

Email

Website

Previous Post
« Variable persistence between pre and post sections in kickstart
Next Post
Extreme predictions by Bill Gates and Nicholas Negroponte »
Powered by Wordpress   |   Lunated designed by ZenVerse