Bash:批量调整图像大小

标签 bash

我正在编写一个 Bash 脚本,它将获取一个目录数组,遍历它,在每个目录中创建一个名为“processed”的目录,并对目录中的每个文件运行一个命令。这是我的代码(阅读代码中的注释以了解我遇到的问题)。有什么想法吗?

#!/bin/bash

command -v convert >/dev/null 2>&1 || {
    echo >&2 "Convert is not installed. Aborting.";
    exit 1;
}

declare -a directories_to_process=(
    "$HOME/Desktop/Album 1"
    "$HOME/Desktop/Album 2"
    "$HOME/Desktop/Album 3"
);

for directory in "${directories_to_process[@]}"
do
    if [ -d "$directory" ]; then
        if [ ! -d "$directory/processed" ]; then
            mkdir "$directory/processed"
        fi

        # Insert code to run the following command on each file in $directory:
        #
        # convert $directory/$filename -resize 108x108^ -gravity center -extent 108x108 $directory/processed/$filename
    fi
done

更新:

这是工作脚本:

#!/bin/bash

command -v convert >/dev/null 2>&1 || {
    echo >&2 "Convert is not installed. Aborting.";
    exit 1;
}

directories_to_process=(
    "$HOME/Desktop/Album 1"
    "$HOME/Desktop/Album 2"
    "$HOME/Desktop/Album 3"
);

for directory in "${directories_to_process[@]}"
do
    [[ -d $directory ]] || continue

    mkdir -p "$directory/processed"

    for infile in "$directory"/*.jpg
    do
        outfile="$directory/processed/${infile##*/}"
        convert "$infile" \
                -resize '108x108^' \
                -gravity center \
                -extent 108x108 \
                "$outfile"
    done
done

最佳答案

在注释掉的地方添加:

for infile in "$directory"/*; do
  outfile="$directory/processed/${infile##*/}"
  convert "$infile" \
      -resize '108x108^' \
      -gravity center \
      -extent 108x108 \
      "$outfile"
done

一些其他注意事项:

  • 与其在 if [ -d "$directory"] 中嵌套大量逻辑,不如考虑将 [[ -d $directory ]] || continue 在循环的顶部以减少嵌套深度。 (与 [ ] 不同,在这种情况下,[[ ]] 中不需要引用)。
  • 而不是测试 [ ! -d "$directory/processed"] 并使用它来决定是否创建目录,考虑无条件运行 mkdir -p "$directory/processed",这将简单地退出如果目录已经存在则为成功状态。
  • 考虑将 command -v convert 替换为 type convert,这比 command -v 语法更为人所知,但具有相同的语法效果。
  • 在函数外声明数组变量时不需要declare -a;只需 directories_to_process=( ... ) 即可。

关于Bash:批量调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10808431/

相关文章:

linux - 仅在 alpine linux 上出现算术语法错误

bash - rsync:如何通过外部排除文件排除具有特殊字符的目录

bash - 在复杂的 bash if 语句中使用 grep 的返回码作为 true false

Linux shell 输出命令到文件

linux - 导出在另一个文件中定义的变量

bash - Perl Regex Query - 过滤文件中超过 18 个月的内容

bash - 使用 tee 将标准输出加载到一行中的变量中

linux - 如何转义变量以用于 sed?

regex - 使用正则表达式的 Bash 变量替换无法按预期工作

arrays - Shell:如何在遍历数组时附加前缀?