Let's say I want to list all php
files in a directory including sub-directories, I can run this in bash:
ls -l $(find. -name *.php -type f)
The problem with this is that if there are no php
files at all, the command that gets executed is ls -l
, listing all files and directories, instead of none.
This is a problem, because I'm trying to get the combined size of all php
files using
ls -l $(find . -name *.php -type f) | awk '{s+=$5} END {print s}'
which ends up returning the size of all entries in the event that there are no files matching the *.php
pattern.
How can I guard against this event?
I suggest you to firstly search the files and then perform the ls -l
(or whatever else). For example like this:
find . -name "*php" -type f -exec ls -l {} \;
and then you can pipe the awk
expression to make the addition.
If you want to avoid parsing ls to get the total size, you could say:
find . -type f -name "*.php" -printf "%s\n" | paste -sd+ | bc
Here is another way, using du
:
find . -name "*.php" -type f -print0 | du -c --files0-from=- | awk 'END{print $1}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With