What am I missing?
I want to find out how many files match a given pattern in a directory and assign it to a variable.
If I type it all straight on the command line it works fine
ls /backups/system\ db\ files/temp/daily/backup_filename_202203*.tar.gz | wc -l
(n.b. the *
is the date the backup was created, e.g. 01
, 02
, 03
etc.)
But as soon as I add it to my bash script it fails.
So far I have:
base_dir="/backups/system\ db\ files/temp"
sub_dir="${base_dir}/daily"
filename_base="backup_filename_"
and I then try and run:
counter=$(ls ${sub_dir}/${filename_base_}202203*.tar.gz | wc -l)
or with quotes:
counter=$(ls "${sub_dir}/${filename_base_}202203*.tar.gz" | wc -l)
The first one fails as it tries to split it based on the whitespaces.
The second one doesn't expand the *
to look for the wildcards.
I have tried just quoting some of it, e.g.
counter=$(ls "${sub_dir}/${filename_base_}"202203*.tar.gz | wc -l)
But again it ignores the wildcard.
I've been searching but for the life of me can't find a way to get the total number of matching files.
filename_base_
doesn't exist. You probably meantcounter=$(ls "$sub_dir/$filename_base"_202203*.tar.gz | wc -l)
. But even that's problematic – Chris Davies Apr 27 '22 at 14:21