I am trying to get the count of files inside a folder for later use in a macro. The problem is the for each loop. I found an old entry by @PeterLewis from 2020:
"You can count the number of files in a folder with:
When I select the "for each path" action it comes back with the "for each item" action. I can select the folder contents collection, but do not see a path. I am also unsure what variable to set as the for each item. Does it matter if I only want the count? The error I get is that KM fails to evaluate the +1 calculation.
It gives me 0. With or without the -1. Just to be sure: I replaced the ~/data with the path to the folder to check. So, edited: ls ~/Users/.../Target PDF | wc -l
What you set the "for each" variable to is, in this case, irrelevant, because you're not using it. And the path is what's returned in the "The items in directory" definition. You can test that by adding a Display Text action in the loop that displays the local_thePath variable (using my example). You'd see one window for every file in the folder, each window showing the full path to that file.
It would be helpful if you could show the command as you have it in the macro, but I suspect a problem with the space in your actual path. You need to enclose the reference in quotes, or backslash the space:
ls ~/Users/.../Target\ PDF | wc -l or ls "~/Users/.../Target PDF" | wc -l
~ means the user's home directory, and so for user account "johnsmith" it is the same as: /Users/johnsmith.
~/Users would mean a folder called "Users" inside your home folder, and I doubt that that is what you mean.
If you select a folder in the Finder, you can drag it into KM (or the Terminal, or whatever...) and the path will be shown as text. That is convenient and a good way to avoid typos.
I think you are right, but IMO it's prudent to include the -1 to explicitly indicate the intent. This is akin to using descriptive variable names in code: not absolutely required, but helpful for lifecycle support.