How to parse a variable number of command line arguments with quotes into eval?

血红的双手。 提交于 2019-12-08 10:14:01

问题


I got this simple script:

#!/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

I run it like this:

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

But when I run it, Sublime Text tries to open a file named My, another named File, and etc. If I replace the eval "${@:2}" with:

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

Then, Sublime Text correctly opens the file "./My File With Spaces in the Name". How to make eval correctly understand all argument quotes with a variable number of command line arguments, i.e., without hard coding "\"$2\" \"$3\" \"$4\" ..."?


回答1:


It's easier to just leave eval out of it:

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

Example:

$ ./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


来源:https://stackoverflow.com/questions/55012282/how-to-parse-a-variable-number-of-command-line-arguments-with-quotes-into-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!