Results 1 to 4 of 4
Hi,
I am abit puzzled with something that appears to be simplest thing to do - increment counter as it goes through "while" cycle. Here is a piece of code ...
- 10-09-2008 #1Just Joined!
- Join Date
- Oct 2008
- Posts
- 9
why variable increment in Shell does not work?
Hi,
I am abit puzzled with something that appears to be simplest thing to do - increment counter as it goes through "while" cycle. Here is a piece of code fragment, all I wan to do is to increment variable "num" and then log the result. But the counter num always shows 0 and I cant understand where is my problem. You might say that the condition if [[ "$filename" == *.xml ]] never happens but it does - the files get moved but the counter does not increase.
Strange is that when I do that straight in command line then it works, but not inside this script. I've tried several other ways to increment a scalar variable but none worked, it always echo-ed that $num = 0:Code:num=0 ls -1 ./$timestamp/$stendname > ./$timestamp/$stendname.lst cat ./$timestamp/$stendname.lst | while read filename do if [[ "$filename" == *.xml ]] then mv "./$timestamp/$stendname/$filename" "./in/$id-$filename" num=$((num+1)) fi done echo -ne "number of retrieved files: $num ;" [ `ls -1 ./$timestamp/$stendname | wc -l` == 0 ] && rmdir ./$timestamp/$stendname || echo -ne "not deleting $stendname directory, some files left! " echo "done."
did not work either..Code:num=$[$num + 1] num=$((num +1))
I know that this must be something simple but I cant figure out anymore.
Ok the script has set -e at the beginning so I can use constructions like command || echo "error" but I dont think it has something to do with it.
Thanks.
- 10-09-2008 #2Linux Guru
- Join Date
- Nov 2007
- Posts
- 1,695
Google => "bash scripting" => First Link
For any Bash scripting needs, bookmark this page.
- 10-09-2008 #3Just Joined!
- Join Date
- Oct 2008
- Posts
- 9
Thanks for the link, I did bookmark it.
I did quick change to my script: (( num = 0 )) and then later in code (( num++ )) but unfortunatelly nothing changed, it still does not increment. I cant understand whats going on there..
In mean time will read thruogh appropriate sections in that LDP project..
I am not first time shell script writer but this one is somewhat special. There must be some very simple mistake, but where..
- 10-09-2008 #4Linux Guru
- Join Date
- Nov 2007
- Posts
- 1,695
Bash Scripting - Loops
Example 10-14
Code:#!/bin/bash var0=0 LIMIT=10 while [ "$var0" -lt "$LIMIT" ] # ^ ^ # Spaces, because these are "test-brackets" . . . do echo -n "$var0 " # -n suppresses newline. # ^ Space, to separate printed out numbers. var0=`expr $var0 + 1` # var0=$(($var0+1)) also works. # var0=$((var0 + 1)) also works. # let "var0 += 1" also works. done # Various other methods also work. echo exit 0


Reply With Quote