我正在尝试编写一个脚本来模仿 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:~>)
我的脚本如下所示(脚本名称是文件大小):
#!/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
在我输入除 q!
以外的任何内容后上面写着$X
使用$(wc -c <$X)
,我必须输入q!
两次以使命令退出。
如何才能让我只需要输入 q!
一次让命令退出,而不是多次输入它来读取文件的大小?
最佳答案
filesize(){ stat -c %s -- "$@";}
如果你坚持要围绕它喋喋不休:
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
然而,该函数本身比 while 循环更具有 Unix 哲学。
wc -c < "$x"
也可以。不同的是stat
将立即告诉您尺寸,无需进行计数。
关于bash - 用于确定文件大小的 Linux 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33989703/