Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 5835  / 1 Year ago, tue, february 14, 2023, 10:39:20

I'm trying to find the number of dirs and files in a given dir. I'm running my bash script like this:



ARCHIVE=/path/to/archive ./myScript


in my script I am doing this:



#find the number of non-empty directories in the given dir 
dirs=$(find $ARCHIVE -mindepth 1 -maxdepth 1 -not -empty -type d | wc -l)
#find the number of files in the given dir
msgs=$(find $ARCHIVE -type f | wc -l)

echo "Number of directories: $dirs"
echo "Total number of messages: $msgs"


This works great when I am running the script on a subset of the data I'm looking at, which is located in a dir at the same level as the script. However, the actual data is in someone else's directory and when I run it with the ARCHIVE variable set to that location, both values return as 0. I have a similar script that I use as well, and the find command there does not work on the second directory either. Strangely enough, I use some egrep commands and they work just fine for both.



Why can I not use find in this manner?


More From » bash

 Answers
6

Try passing the directory you want to search as a parameter to the bash script:



#!/usr/bin/env bash

# First argument to script shall be directory in which to search
ARCHIVE=$1

#find the number of non-empty directories in the given dir
dirs=$(find "$ARCHIVE" -mindepth 1 -maxdepth 1 -not -empty -type d | wc -l)
#find the number of files in the given dir
msgs=$(find "$ARCHIVE" -type f | wc -l)

echo "Number of directories: $dirs"
echo "Total number of messages: $msgs"


Running the script, called dirfiles, on my home directory:



$ ./dirfiles ~
Number of directories: 27
Total number of messages: 8703


And on /usr/lib:



$ ./dirfiles /usr/lib
Number of directories: 161
Total number of messages: 9630


Furthermore, find offers three ways to resolve symbolic links:




  • -P: don't follow symbolic links

  • -L: follow symbolic links

  • -H: don't follow symbolic links except when processing command line arguments.



If you don't want to follow symlinks, but $ARCHIVE happens to be one, then perhaps -H is the way to go.


[#28993] Wednesday, February 15, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dresuitable

Total Points: 69
Total Questions: 116
Total Answers: 122

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
dresuitable questions
Sat, May 15, 21, 04:38, 3 Years ago
Fri, Apr 14, 23, 09:53, 1 Year ago
Tue, May 16, 23, 18:13, 1 Year ago
Sun, Apr 24, 22, 12:59, 2 Years ago
;