我想编写一个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)
< p > -print0
选项会在文件名末尾添加一个空字节终止符,然后使用read
命令读取该终止符。这将确保处理包含特殊字符的文件名时不会出现问题。
find . -type f -name "*.jpg" -exec command {} \;
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