gpt4 book ai didi

linux - 将输出命令保存在变量中并编写 for 循环

转载 作者:可可西里 更新时间:2023-11-01 11:51:32 25 4
gpt4 key购买 nike

我想写一个shell脚本。我使用以下命令行在嵌套子目录中列出我的 jpg 文件:

find . -type f -name "*.jpg"

如何将此命令的输出保存在一个变量中并为此编写一个 for 循环? (我想对每个jpg文件做一些处理步骤)

最佳答案

您不想将包含多个文件的输出存储到一个变量/数组中,然后再对其进行后处理。您可以对正在运行的文件执行这些操作。

假设您有可用的 bash shell,您可以编写一个小脚本作为

#!/usr/bin/env bash
# ^^^^ bash shell needed over any POSIX shell because
# of the need to use process-substitution <()

while IFS= read -r -d '' image; do
printf '%s\n' "$image"
# Your other actions can be done here
done < <(find . -type f -name "*.jpg" -print0)

-print0 选项写入带有空字节终止符的文件名,随后使用 read 命令读取该文件名。这将确保处理包含特殊字符的文件名而不会阻塞它们。

关于linux - 将输出命令保存在变量中并编写 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49014374/

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