Reputation: 31
I am trying to write a script to imitate this script output in linux bash:
(bob@server:~> filesize
Enter a file name (or q! to stop): fee
fee uses 123 bytes.
Enter a file name (or q! to sp): fi
There is no file called fi.
Enter a file name (or q! to stop): foe
foe uses 9802 bytes.
Enter a file name (or q! to stop): q!
bob@server:~>)
My script looks like this (the script name is filesize):
#!/bin/bash
while true; do
read -p "Enter a filename (Or q! to stop) : " X
case $X in
[q!]* ) exit;;
* ) echo "$X uses "$(wc -c <$X)" bytes";./filesize;;
esac
done
After I type anything other than q!
and it reads $X
uses $(wc -c <$X)
, I have to type q!
twice to make the command exit.
How do I make it so that I only have to type q!
once to make the command exit, instead of typing it the multiple times that I read a size of a file?
Upvotes: 2
Views: 107
Reputation: 60185
filesize(){ stat -c %s -- "$@";}
And if you insist on having all the blabber around it:
filesize(){ stat -c %s -- "$@";}
while :; do
read -p "Enter a filename (Or q! to stop) : " x
case "$x" in
'q!') exit;;
*) printf '%s\n' "$x uses $(filesize "$x") bytes";;
esac
done
The function alone is much more Unix philophy than the while loop, however.
wc -c < "$x"
is OK too. The difference is that stat
will tell you the size right away without having to do the counting.
Upvotes: 3