如何将可变数量的带有引号的命令行参数解析为eval?

时间:2019-03-05 22:01:34

标签: bash shell arguments parameter-passing eval

我得到了一个简单的脚本:

#!/usr/bin/env bash
eval "${@:2}"

while [ true ]
do
    FocusApp=`xdotool getwindowfocus getwindowname`

    if [[ "$FocusApp" == *"$1"* ]];
    then
        wmctrl -ir $(xdotool getactivewindow) -b add,maximized_vert,maximized_horz
        break
    fi
done

我这样运行:

$ ./maximize.sh "Sublime Text" /usr/bin/subl -n "./My File With Spaces in the Name"

但是当我运行它时,Sublime Text尝试打开一个名为My的文件,另一个名为File的文件,依此类推。如果我将eval "${@:2}"替换为:

eval "\"$2\" \"$3\" \"$4\" \"$5\" \"$6\" \"$7\" \"$8\""

然后,Sublime Text将正确打开文件"./My File With Spaces in the Name"。如何使eval正确地理解带有可变数量的命令行参数的所有参数引号,即无需硬编码"\"$2\" \"$3\" \"$4\" ..."

1 个答案:

答案 0 :(得分:2)

eval放在其中更容易:

#!/usr/bin/env bash
"${@:2}"

示例:

$ ./myscript "Demo" 'printf' 'This is one argument: %s\n' 'One long arg' 'Another, with * and such'
This is one argument: One long arg
This is one argument: Another, with * and such