0

I have used a FOR loop as a workaround in a batch script to pare a filename stored in a variable down to just its path:

FOR %%f IN ("%f%") DO (SET "o=%tmpdir%\%%~nxf" & SET "d=%%~dpf")
lib\JREPL.BAT "(SourcePath=\q)\.(\q)" "$1%d:$=$$%$2" /XSEQ /f "%f%" /o "%o%"

It seems as if the Parameter Extensions only work when you (ab)use the FOR operator in this way. The following doesn't work:

REM "The following usage of the path operator in batch-parameter substitution is invalid"
ECHO lib\JREPL.BAT "(SourcePath=\q)\.(\q)" "$1%~dpf:$=$$%$2" /XSEQ /f "%f%" /o "%tmpdir%\%~nxf%"

Is this a true limitation of CMD (vs. e.g. PowerShell or a Unix shell), or am I just doing it wrong?

  • 2
    Call it a limitation if you like, but as a `for` variable is not an environment variable, there's no reason to expect them to work in exactly the same way. For example, nobody expects, `%~nxSystemRoot%` or `%~nSystemRoot%` to expand to `Windows` either. – Compo Aug 11 '22 at 16:18
  • Were this Unix, I _could_ run, for instance, `_jrepl 'SourcePath=(\q)\.(\q)' '$1'"${f%/*}"'$2' /XSEQ /f "${f}" /o "${tmpdir}/${f##*/}"`. When I say "limitation", I ask whether local vars are, in Batch scripts, limited _relative to_ parameters and for-loops. Coming from Unix, such limitations on vars-vs-params (if they exist (which is what I am asking)) seems a bit strange. And am I using the correct workaround, anyway? – JamesTheAwesomeDude Aug 11 '22 at 16:34
  • Well it's a bit strange, because they do exist. Essentially, batch files are a simple mechanism for running a batch of individual commands, it was never designed to be a scripting language. – Compo Aug 11 '22 at 18:56
  • It's bad practice to name environment variables with a single letter, because they can easily be confused with `for` meta-variables, which are something completely different; `~`-modifiers are only supported by the latter, and by argument references (like `%1` in a batch file). To me it appears like you are comparing cars with planes, and claiming it's a limitation that cars cannot fly… – aschipfl Aug 12 '22 at 11:53
  • @aschipfl Yes, I've spent my entire life in a world where shell and environment variables are _exactly_ as capable as parameters, so "comparing cars with planes" is a strange analogy. [One can hardly describe Unix as a "flying-car future"...](https://web.mit.edu/~simsong/www/ugh.pdf) – JamesTheAwesomeDude Aug 16 '22 at 19:21

0 Answers0