1

I'm trying to pass commands as an argument to my script

> ./index.bat "echo foo && echo bar"

script:

@echo off
echo %1%
set f=%1%
echo %f%
set f=%f:~1,-1%
echo %f%

output:

"echo foo && echo bar"
"echo foo && echo bar"
bar
echo foo

why is the second part of the command in the argument executed?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Tom Tom
  • 13
  • 1
  • 3
  • 1
    I suggest you study [this guide](https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts) on how cmd.exe parses batch / cmd scripts. – T3RR0R Dec 23 '21 at 14:00
  • 1
    An argument reference is `%1` but not `%1%` (type `call /?` and read)! The result would be the same when you would just put `echo %~1` into the batch file. The reason is that `%`-expansion happens before command recognition. Refer to this post for more information: [How does the Windows Command Interpreter (CMD.EXE) parse scripts?](https://stackoverflow.com/a/4095133) – aschipfl Dec 23 '21 at 14:01
  • If run with `ECHO ON`, there will likely be more information from which to understand what is happening. – lit Dec 23 '21 at 15:06
  • The first argument would be received as `%1`, to remove its surrounding quotes, you'd use `%~1`. Incidentally you are not using the correct method of running two commands after each other, as a one liner, `&&` is a conditional request, you don't want a condition because `echo` cannot fail, so you should be using `&`. Also you want to to print `foo` not `foo`, so remove the additional space character, and finally Windows uses a backward slash for its directory separator so your input command should read as `.\index.bat "echo foo& echo bar"` and `index.bat` would contain just: `@%~1`. – Compo Dec 23 '21 at 15:41
  • Please note however that the idea of just running an input argument as a command is very risky ground, there is nothing to stop a an accidental, or deliberately malicious entry. _(Although TBF, the same person could I suppose enter it into their own prompt)_ This would however be a potentially problematic idea, if your index.bat contained a method of self elevation, thus opening your system to attacks from a less privileged user level. – Compo Dec 23 '21 at 15:50
  • There is a method described [here](https://www.dostips.com/forum/viewtopic.php?t=4288#p23980) which allows the safe definition of a variable without the input argument being expanded in the process. – T3RR0R Dec 23 '21 at 15:55
  • The only line of code you need in your batch file if you want the two echo commands to execute is `%~1` – Squashman Dec 23 '21 at 19:54

0 Answers0