Search code examples
bashshellvariablesscript-fu

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 $image 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 :)


Solution

  • 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}