bash - 用于确定文件大小的 Linux 脚本

标签 bash shell

我正在尝试编写一个脚本来模仿 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/

相关文章:

shell - 如何一起使用 expect 和 shell 脚本

bash - 如何递归地转到每个文件夹并执行同名的 shell 脚本?

javascript - 如何使用shell在gulp中读取?

linux - MySQL将不会开始使用Dockerfile

python - 激活 virtualenvwrapper 并在登录时运行 ssh-agent

string - 在 Bash 中比较两个字符串时出现 "command not found"错误

linux - 为什么这是语法错误?

php - 如何防止 php "exec"参数中的恶意注入(inject)(webhook -> bash 脚本)

c - 如何从C程序执行命令

linux - 如何删除文件中的匹配行?