0

I have a small bash script that does simple file modifications and I want to rewrite the code to be more readable. My goal is to pass Commands as strings into a function that loops the command over a Directory.

I've tried to use different methods to escape the "$" or different """ combinations but none really work.

#!/bin/bash
process="/Users/Gernot/Tools/.Process"
output="/Users/Gernot/Tools/2 Output"
input="/Users/Gernot/Tools/1 Input/"

function run {

    for file in "$input$1"/*
    do
        echo "running procedure $1" #echoes which procedure is running
        $2 #does the command for every file in the directory

    done


}



run "PDF Komprimieren" "magick convert \$file -density 110 -compress jpeg -quality 100 \$file"

This is the error I get:

running procedure PDF Komprimieren
convert: unable to open image '$file': No such file or directory @ error/blob.c/OpenBlob/3497.
convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/556.
convert: no images defined `$file' @ error/convert.c/ConvertImageCommand/3273.
8
  • you can use eval, eg. $(eval echo "$input/$1). It looks like you want to loop through your args as well Commented Aug 1, 2019 at 6:24
  • 1
    Don't pass commands as strings but make different functions like pdf_komprimieren() and magick_convert() which will be, IMHO, more readable. Even when you get your command evaluated, the spaces in the dirname and perhaps filename will cause more problems. Commented Aug 1, 2019 at 6:24
  • First, I would like to point out that it is a bad practice. The simple hack would be using the evil eval before $2. Commented Aug 1, 2019 at 6:24
  • @jenesaisquoi No I don't want to loop through my args. I'll try your tip thanks Commented Aug 1, 2019 at 6:29
  • 1
    Storing commands as strings is hard to get right in complex cases; see BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail! Commented Aug 1, 2019 at 7:38

1 Answer 1

1

Try using functions like

pdf_komprimieren() {
   find "PDF Komprimieren" -maxdepth 2 -type f -print0 |
     xargs --null -n1 -Ifile magick convert "file" -density 110 -compress jpeg -quality 100 "file"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.