Skip to content
Advertisement

Bash script – Loop through directory with regex

I’m sure this must be possible, but I’m not sure how. What I’m trying to do is loop through a directory, looking for numeric directories within, and get their disk space. This is what I’ve come up with, but it’s not dealing with the regex.

FILES="$DIR_PATH/secure/{[0-9]+}"
for f in $FILES
do
   used=`du -s $f`
   base=`basename $f`
   mysql --user=$DB_USER --password=$DB_PASS --host=$DB_HOST $DB_NAME << EOF
       INSERT INTO disk_usage(site_id, filesystem, used, size) VALUES("$base", "Private Files", "$used", "$size")
EOF
done

In case it’s not clear, I have a directory containing a bunch of directories with numeric names. This directory also contains some other files/directories that I don’t want to calculate disk space on. So I just want to loop through the directory and get the disk space used by each numeric subdirectory. I’m sure this isn’t optimal code, but it’s being run privately on a safe filesystem, so the risk of problems is pretty low, but if there is a way to improve it, please let me know.

Advertisement

Answer

Using bash’s extended patterns

shopt -s extglob
for subdir in "$DIR_PATH"/secure/+([[:digit:]])/
# ...............................^^-----------^
...

Note the trailing slash: that limits the results to directories only, ignoring files named with all digits.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement