my for loop in bash is not counting files and directories

Solution for my for loop in bash is not counting files and directories
is Given Below:

I’m writing a small script in bash to practice, I find the syntax of my code correct but I’m surely missing something, this is my code:

#!/bin/bash

cfiles=$(ls | wc -l)

echo $cfiles

files=0
dirs=0

for look in $(ls); do
   [ -d look ] && $((++dirs)) || $((++files))
done

echo "Files: $files"
echo "Directories: $dirs"

I’m receiving a long error message and wrong output:

22
test.sh: line 11: 1: command not found
... (until number 48)
test.sh: line 11: 48: command not found
Files: 48
Directories: 0

What’s wrong with my code? It reaches a count of 48 with command not found, but there are 22 files excluding . and .. then it’s doubling the number.

Thank you very much for helping!

$((++dirs)) expands to a number, which is then executed as a command, hence the error 1: command not found.

To just execute ++dir without expanding the result, use ((++dir)) without the $. Same for ++files.

It reaches a count of 48 with command not found, but there are 22 files

Then your file names contain whitespace or special symbols like *[]?. See Why you shouldn’t parse the output of ls.

You can make your script a lot simpler and safer by using globs instead of ls. Also, the loop is not necessary with arrays or a function that counts its arguments.

#! /bin/bash
count() { echo $#; }
total=$(count *)
dirs=$(count */)
((files=total-dirs))

Compare how the shell handles expansion:

$ ls -t
'this file'   file  'this directory'   directory
$ for f in $(ls) ; do echo "[$f]" ; done
[directory]
[file]
[this]
[directory]
[this]
[file]
$ for f in * ; do echo "[$f]" ; done
[directory]
[file]
[this directory]
[this file]

So in one line:

$ dirs=0; files=0; for f in * ; do [ -d "$f" ] && ((++dirs)) || ((++files)) ; done ; echo "d: $dirs f: $files"