Bash脚本如果条件

时间:2017-07-06 11:47:02

标签: bash shell grep boolean

我需要检查图片的分辨率是否为 900x900像素且文件名不允许包含 _thumb _v

我想用这条线做什么:
如果图片是900x900像素并且不包含_v或_thumb =>在文件扩展名之前将_thumb一词添加到文件名的末尾。

线条就是这样:

if file $picture | grep -q 900x900 && ! file $picture | grep -q _thumb && ! file $picture | grep -q _v;

脚本:

#Change to current .sh directory
cd -P -- "$(dirname -- "$0")"
for picture in */*/Templates/*.jpg
do
    filename=${picture##*/}
    filename1=$(echo "$filename" |sed 's/.\{4\}$//')
    parent_dir="$(dirname -- "$(/usr/local/bin/realpath "$picture")")"

    #Colors
    red=`tput setaf 1`
    green=`tput setaf 2`
    magenta=`tput setaf 5`
    reset=`tput sgr0`


    if file $picture | grep -q 900x900 && ! file $picture | grep -q _thumb && ! file $picture | grep -q _v;
        then
            mv -v "$picture" "$parent_dir/"$filename1"_thumb.jpg"
            echo "${green} [PASS] $filename1 Thumbnail 900x900 found and renamed ${reset}"
        else
            echo "${magenta} [WARNUNG] $filename1 contains _thumb already or is a _v picture or isn't 900x900 pixels ${reset}"
        fi

2 个答案:

答案 0 :(得分:0)

我看到一些问题。 #3,#4和#5是最重要的。

  1. 第一行中的目标shell
  2. 您需要使用for
  3. 完成done循环
  4. 您需要转义$filename1上的内部双引号。周围的引号目前没有引用此内容。
  5. 双引号中的变量
  6. 澄清您是否正在查找图片大小或仅仅是文件中包含900x900?导致grep -q 900x900无法找到图片大小的原因。您需要像其他人提到的那样将它与imagemagik identify结合使用。
  7. 修复:

    #!/bin/bash
    #Change to current .sh directory
    cd -P -- "$(dirname -- "$0")"
    for picture in */*/Templates/*.jpg 
    do
        filename=${picture##*/}
        filename1=$(echo "$filename" |sed 's/.\{4\}$//')
        parent_dir="$(dirname -- "$(/usr/local/bin/realpath "$picture")")"
    
        #Colors
        red=`tput setaf 1`
        green=`tput setaf 2`
        magenta=`tput setaf 5`
        reset=`tput sgr0`
    
    
        if file "$picture" | grep -q 900x900 && ! file "$picture" | grep -q _thumb && ! file "$picture" | grep -q _v;
            then
                mv -v "$picture" "$parent_dir/\"$filename1\"_thumb.jpg"
                echo "${green} [PASS] $filename1 Thumbnail 900x900 found and renamed ${reset}"
            else
                echo "${magenta} [WARNING] $filename1 contains _thumb already or is a _v picture or isn't 900x900 pixels ${reset}"
            fi
    done
    

答案 1 :(得分:0)

不要使用“file $ picture | grep 900x900”,因为您不知道文件名是否包含900x900。我建议使用ImageMagick包中存在的命令标识,如:

if [[ "900 900" == $(identify -format '%w %h' "$picture") ]] ; then
  if [[ $picture != *_v.jpg && $picture != _thumb.jpg ]] ; then
    mv "$picture" "${picture%.jpg}_thumb.jpg"
  fi
fi

我假设_v和_thumb在扩展之前出现,我稍微偏离了你的规范。我认为避免像best_view.jpg这样的意外比赛更为谨慎。

PS:当文件名或dirnames中有空格时,请始终检查脚本是否有效。