How to parse a variable number of command line arg

2019-06-09 03:48发布

问题:

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