在shell脚本中混合命令和变量

时间:2011-02-28 14:25:04

标签: bash shell variables script-fu

我需要一个非常简单的shell脚本来处理文件夹上的所有图像并更改其大小。图像处理是使用gimp script-fu完成的,shell脚本必须做的唯一事情是for循环。

我做到了:

#!/bin/sh

mkdir processed
for image in `ls`
do
    if [ $image != "script.sh" ]
    then
        if [ $image != "processed" ]
        then
            gimp -i -b '(let* ( (img (gimp-file-load 1 "1.jpg" "1.jpg")) (drw (gimp-image-get-active-drawable (car img))) ) (gimp-image-scale-full 1 400 300 3) (file-jpeg-save 1 (car img) (car drw) "processed/1.jpg" "1.jpg" 0.6 0 1 1 "" 3 0 0 2) (gimp-quit 0) )'
        fi
    fi
done

这段代码有效但是,在脚本fu代码中我把1.jpg作为文件名,当然,我希望看到$ image变量的值。我的shell脚本知识是有限的,我失去了我必须将变量放在命令中的方式。

你能帮帮我吗?谢谢你的时间:))

3 个答案:

答案 0 :(得分:2)

使用for image in *代替ls

要将变量传递给Gimp脚本并保留Gimp的引号,您需要对外部引号使用双引号并转义内部引号:

gimp -i -b "(let* ( (img (gimp-file-load 1 \"$image\" \"$image\")) (drw (gimp-image-get-active-drawable (car img))) ) (gimp-image-scale-full 1 400 300 3) (file-jpeg-save 1 (car img) (car drw) \"processed/$image\" \"$image\" 0.6 0 1 1 "" 3 0 0 2) (gimp-quit 0) )"

您还可以简化脚本:

mkdir processed
for image in *.jpg
do
    if [[ -f $image ]]
    then
        gimp ...
    fi
done

如果您想要添加更多扩展程序:

for image in *.{jpg,JPG,jpeg,JPEG,gif,GIF,png,PNG}

答案 1 :(得分:2)

另一种可能更具可读性的方法:

mkdir processed

gimp_script_template='(let* ( 
    (img (gimp-file-load 1 "%s" "%s")) 
    (drw (gimp-image-get-active-drawable (car img))) 
  ) 
  (gimp-image-scale-full 1 400 300 3) 
  (file-jpeg-save 1 (car img) (car drw) "processed/%s" "%s" 0.6 0 1 1 "" 3 0 0 2) 
  (gimp-quit 0) 
)'

for img in *; do
    [ ! -f "$img" ] && continue
    [ "$img" = "script.sh" ] && continue
    gimp_script="$( printf "$gimp_script_template" "$img" "$img" "$img" "$img" )"
    gimp -i -b "$gimp_script"
done

答案 2 :(得分:0)

你可以尝试

"'(let* ( (img (gimp-file-load 1 "$image" "$image")) (drw (gimp-image-get-active-drawable (car img))) ) (gimp-image-scale-full 1 400 300 3) (file-jpeg-save 1 (car img) (car drw) "processed/$image" "$image" 0.6 0 1 1 "" 3 0 0 2) (gimp-quit 0) )'"