So if we want to stay as close as possible to your current approach, we could do it like this:
#!/bin/bash
FILE="$(ls -S "$1")"
for f in $FILE
do
file_size_bytes=$(du "$f" | cut -f1)
echo "$f"
if [[ "$file_size_bytes" -eq 0 ]]
then
read -r -p "Would you like to delete the zero-byte file ${f}? [Y/n]: " input
if [[ "$input" = [Yy] ]]
then
rm "$f"
fi
fi
done
Another answer used stat
, but stat
isn't POSIX or portable, but if you're only running under Linux, stat
is a good approach.
In the above example, read -p
is used to prompt the user for input, and store the result in $input
. We use [[ "$input" = [Yy] ]]
to see if the input is either Y
or y
.
The way it's currently written, you have to type y
or Y
and press enter to delete the file. If you want it to happen as soon as the user hits y
or Y
, add -n 1
to read
to make it only read one character.
You also don't need to use ${var}
unless you're putting it inside another string, or if you need to use some kind of parameter expansion.
As a side note, this sounds like it's some type of homework or learning experience, so, please look up every command, option, and syntax element in the above and really learn how it works.