Sample Header Ad - 728x90

Strange variable scope behavior when calling function recursivly

3 votes
1 answer
568 views
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
Asked by Shlomo V (43 rep)
Sep 3, 2024, 07:39 PM
Last activity: Sep 4, 2024, 01:24 PM