Bash:获取数组中元素的数量,这是"ls"命令的结果?${#a[@]} 不起作用



我正在从数组中的当前目录中获取 15 个最新的.jpg.png文件:

images=$(ls -1tr *.jpg *.png | tail -n 15)

在这种情况下似乎工作正常:

for i in ${images[*]}; do echo "Found this image: $i"; done

它向我显示 15 行为:

找到这张图片: foo.jpg找到这张图片:


bar.png
找到这张图片: baz.jpg
(...等等...

但是,当我尝试像这样打印$images数组的长度时:

echo ${#images[@]}

我总是得到:

1

尽管发现了多个图像,并且上述for遍历$images数组确实显示了多行。

我做错了什么?如何获取数组中的元素数?

您正确地获得了元素的数量,它确实是 1。

既然你了解 JS,下面是你的 JavaScript 代码,看看实际发生了什么:

// Assign all filenames to a single index
var images = ["foo.jpgnbar.jpgnbaz.jpg"]
// Join all the elements on spaces, then split them up on whitespace
var elements = images.join(" ").split(/[ tn]/);
for (var i in elements) {
console.log("Found this image: " + elements[i]);
}
console.log("Array length: " + images.length);

输出:

Found this image: foo.jpg
Found this image: bar.jpg
Found this image: baz.jpg
Array length: 1

以下是您在 Bash 中打算执行的操作:

images=( $(ls -1tr *.jpg *.png | tail -n 15) )
for i in "${images[@]}"; do echo "Found this image: $i"; done
echo "${#images[@]}"

解析ls输出被认为是脆弱的:上面的代码仍然在空格上拆分,所以My Image.jpg会变成MyImage.jpg

可悲的是,当您需要按修改日期排序的文件时,没有简单、好的替代品,但这避免了文件包含*或空格 (Bash 4+) 时出现问题:

mapfile -t images < <(ls -tr *.jpg *.png | tail -n 15)
for i in "${images[@]}"; do echo "Found this image: $i"; done
echo "${#images[@]}"

最新更新