gpt4 book ai didi

linux - 遍历 bash 中的参数

转载 作者:太空宇宙 更新时间:2023-11-04 10:15:07 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com