如何将变量作为字符串传递到bash中的函数中?

如何将变量作为字符串传递到bash中的函数中?,bash,macos,shell,Bash,Macos,Shell,我有一个小的bash脚本,可以进行简单的文件修改,我想重写代码,使其更具可读性。我的目标是将命令作为字符串传递到一个函数中,该函数在目录上循环该命令 我曾尝试使用不同的方法来逃避“$”或不同的“%”组合,但没有一种方法真正起作用 #!/bin/bash process="/Users/Gernot/Tools/.Process" output="/Users/Gernot/Tools/2 Output" input="/Users/Gernot/Tools/1 Input/" function

我有一个小的bash脚本,可以进行简单的文件修改,我想重写代码,使其更具可读性。我的目标是将命令作为字符串传递到一个函数中,该函数在目录上循环该命令

我曾尝试使用不同的方法来逃避“$”或不同的“%”组合,但没有一种方法真正起作用

#!/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"
这是我得到的错误:

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.

尝试使用如下函数

pdf_komprimieren() {
   find "PDF Komprimieren" -maxdepth 2 -type f -print0 |
     xargs --null -n1 -Ifile magick convert "file" -density 110 -compress jpeg -quality 100 "file"
}

您可以使用
eval
,例如
$(eval echo“$input/$1)
。看起来您也想在参数之间循环,而不是以字符串形式传递命令,而是生成不同的函数,如
pdf\u komprimieren()
magick\u convert()
,这将更具可读性。即使在对命令求值时,dirname和filename中的空格也可能会导致更多的问题。简单的破解方法是在
$2
之前使用邪恶的
eval
@jenesaisquoi不,我不想循环我的参数。我将尝试您的技巧,感谢保存命令,因为字符串在复杂情况下很难正确处理;看见