开发者

Mix command and variables in shell scripting

I need a very simple shell script that processes all images on a folder and changes its size. The image processing is done with gimp script-fu and the only thing that the shell script have to do is the for loop.

I made this:

#!/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

This code works but, in the script-fu code I put 1.jpg as the file name and, of course, I want that there appears the value of the $imag开发者_如何转开发e variable. My shell scripting knowledge is limited and I'm lost with the way I have to put the variable inside the command.

Can you help me? Thanks for your time :)


Use for image in * instead of ls.

To pass the variable to the Gimp script and preserve the quotes for Gimp, you'll need to use double quotes for the outer ones and escape the inner quotes:

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) )"

You can also simplify your script:

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

If you want to include more extensions:

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


Another approach that may be more readable:

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


you can try

"'(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) )'"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜