EDIT: sorry. this is my first question here.
Here is a minimal working example
#!/bin/bash
#
count=0
function something() {
if test -f "$1"; then
# is a file
((count++))
echo $count $1
elif test -d "$1"; then
# is a folder
find $1 | while read line; do
if [ $1 != $line ]; then # first line in find is the folder itself. prevent infinte recursion
something $line
fi
done
fi
}
while [ $# -gt 0 ]
do
something "$1"
shift
done
echo "Processed $count files"
Example output:
$ ./test.sh *
1 0/file1.txt
2 0/file2.txt
1 1/file1.txt
2 1/file2.txt
1 2/file1.txt
2 2/file2.txt
1 3/file1.txt
2 3/file2.txt
1 4/file1.txt
2 4/file2.txt
1 5/file1.txt
2 5/file2.txt
1 6/file1.txt
2 6/file2.txt
1 7/file1.txt
2 7/file2.txt
1 8/file1.txt
2 8/file2.txt
1 9/file1.txt
2 9/file2.txt
1 test.sh
Processed 1 files
As you can see each time I call the function recursively it returns to the variable state on parent function and messes up the count.
Using Ubuntu 22.06 on WSL2 VM
localanywhere? Ordeclareinside a function? If not, then the variable is global. No there is no separate global scope.unpackhave to do withAandB? (2) What do the command-line parameters have to do with anything? Do they affect the control flow? (3) It’s hard to debug “sometimes”. Can you clarify? (4) For a given scenario, is the result consistent? (5) Can you give a runnable example that demonstrates the problem (perhaps including tests on"$1"that determine whetherAcalls itself orB)? … (Cont’d)echostatements toecho "A: $count"andecho "outside: $count". Addecho "B: $count",echo "Calling A with arg xxx"andecho "Calling B"in the appropriate places.