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

问题描述 投票:0回答:1

我有这个简单的脚本:

#!/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\" ..."

bash shell arguments parameter-passing eval
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.