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

时间:2018-02-27 17:15:41

标签: linux bash shell

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

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

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

2 个答案:

答案 0 :(得分:3)

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

假设您有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命令读取该字节终结符。这将确保处理包含特殊字符的文件名而不会阻塞它们。

答案 1 :(得分:1)

比存储在变量中更好,请使用:

find . -type f -name "*.jpg" -exec command {} \;

即使如果你愿意,命令也可以是一个完整的shell脚本。

演示比解释更好,不是吗?复制粘贴终端中的整行:

cat<<'EOF' >/tmp/test
#!/bin/bash

echo "I play with $1 and I can replay with $1, even 3 times: $1"
EOF
chmod +x /tmp/test
find . -type f -name "*.jpg" -exec /tmp/test {} \;

编辑:新演示(来自评论的新问题)

find . -type f -name "*.jpg" | head -n 10 | xargs -n1 command

(这个另一个解决方案没有处理带有换行符或空格的文件名)

这个照顾:​​

#!/bin/bash

shopt -s globstar

count=0

for file in **/*.jpg; do
    if ((++count < 10)); then
        echo "process file $file number $count"
    else
        break
    fi
done
相关问题