linux - 遍历 bash 中的参数

标签 linux bash shell while-loop parameters

我正在编写一个脚本,它接受一些文件作为参数,并为每个文件输出一条消息:

FILENAME 的大小为 SIZE 千字节

我正在为如何在 while 循环中引用参数而苦苦挣扎

这是我的代码

i=1
while [ $i -le $# ]
do
echo "The size of $(du -s $1 | cut -f2) is $(du -s $1 | cut -f1) kilobytes"
i=$((i+1))
done

最佳答案

只是遍历值,而不是索引。请注意,这都是 POSIX 标准 shell 。

for i in "$@"; do
    # Run du once, no need for cut
    read -r size dir <<EOF
$(du -s "$i")
EOF
    echo "The size of $dir is $size kilobytes"
done

您可以在 bash 中用此处字符串替换此处文档:

read -r size dir <<< "$(du -s "$i")"

关于linux - 遍历 bash 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46745525/

相关文章:

linux - shell 内的 shell 脚本 shell

linux - BASEDIR 环境变量未正确定义

linux - 如何判断破折号的版本号?

linux - 如何设置 bash 脚本在 linux ubuntu 服务器运行时随时在后台运行

bash - incrond在CentOS 6.4下运行但不执行命令

linux - 在linux中根据搜索列显示整行的命令?

shell - 重启后 chmod -> 权限更改

linux - 无法在 Heritrix3 Web Crawler 中运行并行作业

Linux 和 Primesense

bash - 嵌套ssh中bash shell脚本中的命令行参数