A number of issues in your code:
- Don't parse ls
- Quote variables in large majority of cases
- Don't use temp files when they're not needed
- Use already made tools like du for this (see comments)
Assuming you're just wanting to get practice at this and/or want to do something else other than what du already does, you should change syntax to something like
#!/bin/bash
dir="$1"
[[ $dir == *'/' ]] || dir="$dir/"
if [[ -d $dir ]]; then
echo "Directory <$1> contains the following files:"
else
echo "<$1> is not a valid directory, exiting"
exit 1
fi
shopt -s dotglob
for file in "$dir"*; do
if [[ -f $file ]]; then
echo "file: [$file]"
((size+=$(stat -c%s "$file")))
fi
done
echo "$size"
Note:
- You don't have to pre-allocate variables in bash,
$size
is assumed to be 0 - You can use
(())
for math that doesn't require decimal places. - You can use globs (
*
) to get all files (including dirs, symlinks, etc...) in a particular directory (and globstar**
for recursive) shopt -s dotglob
Is needed so it includes hidden.whatever
files in glob matching.