I have 100 folders (called "Folder_1", "Folder_2", "Folder_3", ...) containing several files. From a loop over each folder, I would like to run commands (i.e., display the folder name) depending on conditions (i.e., number of files in the folder is not equal to 20133). Here is my code:

for f in *Folder*/; do cd "$f"; if ["$(find . -type f | wc -l)" -ne 20133]; then echo "$f" && cd ..; fi; done

However, I have these error messages:

-bash: cd: Folder_1/: No such file or directory
-bash: [20133: command not found

Your problem is in the fact that you always enter the current directory (cd "$f") but only go back up one directory if you score a hit (then echo "$f" && cd ..).

This is what I did to create a test environment and write a working example:

johan@iMac:~$ mkdir -p example/Folder_{1..20}
johan@iMac:~$ touch example/Folder_{1..20}/file_{1..10}
johan@iMac:~$ touch example/Folder_{18..20}/file_{11..15}
johan@iMac:~$ cd example
johan@iMac:~/example$ for f in Folder_*; do test "$(find "$f" -type f | wc -l)" -eq 15 && echo "$f"; done
johan@iMac:~/example$ cd ..
johan@iMac:~$ rm -rf example/

Note that I used the built in test instead of the [ ... ] syntax to improve readability. Fun fact, the [ character is just a program, and is the same as the test program. That is the reason it needs spaces around its arguments :)

Here check this out (On my iMac)

johan@iMac:~$ md5 /bin/test
MD5 (/bin/test) = 2c4b51263409bd39f1ea0fa4f925130a
johan@iMac:~$ md5 /bin/[
MD5 (/bin/[) = 2c4b51263409bd39f1ea0fa4f925130a

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.