0

I'm new to bash scripting, and I found this example on stackoverflow. Now, it seems this is what I need however, I'm unsure of a few things.

  1. How would I properly modify it to display the number of files and folders in the downloads directory

  2. What does the "$@" mean?

My code so far:

cleanPath="/home/someuser/Downloads/*"

if [ -d $cleanPath]; then
    find "$cleanPath" -type f | ls -l $cleanPath | wc -l | echo "Number of files is $@"
    find "$cleanPath" -type d | ls -l $cleanPath | wc -l | echo "Number of directorieis $@"
fi

1 Answer 1

1

You're nearly there, but you have some syntax errors (spaces needed around if statement brackets) and some other mistakes. cleanPath="/home/someuser/Downloads/*" can cause problems if you don't properly quote cleanPath like "$cleanPath" because the shell expands *, so you actually get a list of all files and directories in Downloads (try echo $cleanPath and you will see). Also, I don't see why you pass the output of find to ls, ls will not even use the input, it will just list all the files and directories.

Try this:

cleanPath="/home/someuser/Downloads"

if [ -d "$cleanPath" ]; then
  echo "No of files is ""$(find "$cleanPath" -mindepth 1 -type f | wc -l)"
  echo "No of directories is ""$(find "$cleanPath" -mindepth 1 -type d | wc -l)"
fi

Be aware this is recursive - default find behaviour. You didn't make it clear whether that was what you wanted. For a non recursive list:

cleanPath="/home/someuser/Downloads"

if [ -d "$cleanPath" ]; then
  echo "No of files is ""$(find "$cleanPath" -mindepth 1 -maxdepth 1 -type f | wc -l)"
  echo "No of directories is ""$(find "$cleanPath" -mindepth 1 -maxdepth 1 -type d | wc -l)"
fi

Also you can use $@ as an array representation of all the positional parameters passed to a script.

https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#index-_0024_0040

Beware: -mindepth -maxdepth are not POSIX compliant, and this doesn't work for files with newlines.

Sign up to request clarification or add additional context in comments.

11 Comments

It works, BUT, it says that they're 2 directories in Downloads, when in fact it is only 1 directory. What is this?
The first one is recursive. Also I fixed a mistake. I guess you want the second example
Perfect, the second one is what I want. One more questions, and sorry I didn't mention it before, is it possible to capture the results in variables for example the number of files in one variable and the number of directories in another?
@CharlesWhitfield pass it to the variable, i.e. VAR=$(...). VAR must start at the beginning of the line, and no space before and after =.
@gniourf_gniourf No it's not wrong, not on my OS. Have you actually tried it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.