1

I am using Konsole on kubuntu 14.04.

I want to take arguments to this shell-script, and pass it to a command. The code is basically an infinite loop, and I want one of the arguments to the inner command to be increased once every 3 iterations of the loop. Ignoring the actual details, here's a gist of my code:

#!/bin/bash
ct=0
begin=$1
while :
    do
        echo "give: $begin as argument to the command"
        #actual command
        ct=$((ct+1))
        if [ $ct%3==0 ]; then
            begin=$(($begin+1))
        fi
    done

I am expecting the begin variable to be increased every 3 iterations, but it is increasing in the every iteration of the loop. What am I doing wrong?

taninamdar
  • 137
  • 1
  • 8

2 Answers2

1

You want to test with

if [ $(expr $cr % 3) = 0 ]; then ...

because this

[ $ct%3==0 ]

tests whether the string $ct%3==0, after parameter substitution, is not empty. A good way for understanding this is reading the manual for test and look at the semantics when it is given 1, 2, 3 or more arguments. In your original script, it only sees one argument, in mine it sees three. White space is very important in the shell. :-)

Jens
  • 69,818
  • 15
  • 125
  • 179
1

In BASH you can completely utilize ((...)) and refactor your script like this:

#!/bin/bash

ct=0
begin="$1"
while :
do
   echo "give: $begin as argument to the command"
   #actual command
  (( ct++ % 3 == 0)) && (( begin++ ))
done
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • I know, but even after writing #!/bin/bash, I think it's not using bash. That's why I used ct=$((ct+1)), which is the only one from http://askubuntu.com/questions/385528/how-to-increment-a-variable-in-bash that works. – taninamdar Feb 03 '15 at 07:40