简体   繁体   中英

Bash Scripting - Display number of files and folders in a directory

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM