Bash Math variables not working

I have a simple bash script that is part of the embedded web application that I developed.

The goal is to automate the removal of image thumbnails when the user image has been deleted.

script writes some basic status information to a file /var/log/images.log

#!/bin/bash
cd $thumbpath
filecount=0
# Purge extraneous thumbs
find . -type f | while read file
do
  if [ ! -f "$imagepath/$file" ]
  then
    filecount=$[$filecount+1]
    rm -f "$file"
  fi
done
echo `date`: $filecount extraneous thumbs removed>>/var/log/images.log

While the script correctly removes the thumbs, it incorrectly displays the number of fingers removed, it always shows 0.

For example, only by manually creating several orphan sketches, and then running my script, manually deleted big blue ones are deleted, but the log shows:

Thu Jun 9 23:30:12 BST 2011: extraneous thumbs removed

What am I doing wrong that stops $ filecounter from showing a non-zero number when files are deleted .

bash script, , , 0, 1:

#!/bin/bash
count=0
echo $count
count=$[$count+1]
echo $count

Edit:

,

$ x=3
$ x=$[$x+1]
$ echo $x
4

... , script?

:

count=0
echo Initial Value $count
for i in `seq 1 5`
do
  count=$[$count+1]
  echo $count
done
echo Final Value $count


Initial Value 0
1
2
3
4
5
Final Value 5

count=$[$count+1] count=$((count+1)), script.

+3
3

. $(( ... )), :

$ x=4
$ y=$((x + 1))
$ echo $y
5
$


, , . ( ksh, , ). bash, , , , ​​ . , ( , ).

, filecount :

#!/bin/bash

filecount=0
ls /bin | while read x
do
        filecount=$((filecount + 1))
        echo $filecount
done
echo $filecount

... , , , ( while).

- ...

#!/bin/bash

filecount=0
filecount=`ls /bin | while read x
do
        filecount=$((filecount + 1))
        echo $filecount
done | tail -1`
echo $filecount

, - stdout , ( filecount). , stdout stdin .

, -pokery. , : -)

+6

while, bash, .

:

filecount=0
find . -type f | while read file; do
  if [ ! -f "$imagepath/$file" ]; then
    filecount=$[$filecount+1]
    rm -f "$file"
  fi
done
echo $filecount

:

filecount=0
while read file; do
  if [ ! -f "$imagepath/$file" ]; then
    rm -f "$file" && (( filecount++ ))
  fi
done < <(find . -type f)
echo $filecount

, find . :

files=$( find . -type f )
while ...; do
  : 
done <<< "$files"
+2

Chris J is absolutely right that you are using the wrong operator, and POSIX is a sub-sub-variable, which means that you cannot get the final score.

As a side note, when performing mathematical operations, you can also consider using the type t20> shell bultin as follows:

$ filecount=4
$ let filecount=$filecount+1
$ echo $filecount
5

Also, if you want the scope to work just as you expected, despite this pipeline, you can use zsh instead of bash. In this case, it should be a reduction in substitution and work as expected.

+1
source

All Articles