0

I'm trying to write a Bash function which will take some arguments from the command line and put them in a URL which contains URL parameters (i.e. contains ? and &).

If there is only one parameter in the URL, there is no &, and there is no problem, i.e., if I define the following function:

test() {
    cmd.exe /c start https://example.com/\?foo=$1
}

and invoke it with test bar, it opens the URL https://example.com/?foo=bar in my browser, which is completely correct.

The problem is when I want to add a second URL parameter. I then extend the function as follows:

test() {
    cmd.exe /c start https://example.com/\?foo=$1\&baz=$2
}

but when I invoke it with test bar qux, the same URL as before (https://example.com/?foo=bar) is opened in my browser, and my terminal displays the error 'baz' is not recognized as an internal or external command, operable program or batch file.

Wrapping the URL in double quotes also does not help: when I change it to

test() {
    cmd.exe /c start "https://example.com/\?foo=$1\&baz=$2"
}

it opens the URL https://example.com//?foo=bar", and I still get the error 'baz' is not recognized as an internal or external command, operable program or batch file.

3

Since cmd.exe is invoked with a command, the cmd.exe escape syntax needs to be used, rather than the Bash escape syntax, i.e. & needs to be escaped as ^& (and ? does not need escaping). The following works as intended:

test() {
    cmd.exe /c start "https://example.com/?foo=$1^&baz=$2"
} 

(Note that 'baz' is not recognized as an internal or external command, operable program or batch file. is an error generated by cmd.exe: it refers to a batch file, which is a Windows concept.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.