Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

create an alias with optional parameter

Jun
137
3
I'm trying to create a simple alias that calls a program with the parameter(s) passed to it, after massaging them slightly. The first parameter is required, and the second is optional. If the second is not supplied, I want to take the first parameter, use just its filename, and prepend the _cwd. Both parameters must be properly quoted, if needed, and both must be full paths, not relative.

Here is what I created, but it doesn't work if the second isn't supplied, complaining about not being able to find %2 that won't exist. In other words, it's not doing short-circuit evaluation, because it shouldn't need to do the second part of the @if because the conditional evaluates true. How do I change this to work properly?

RichCopy="c:\Program Files (x86)\Microsoft Rich Tools\RichCopy 4.0\RichCopy.exe" %@quote[%@full[%1]] %@if[%# == 1,%@quote[%_cwd\%@filename[%1]],RichCopy %1 %@full[%2]]
 
Last edited:
Aliases don't do short circuit evaluation. They evaluate the entire command line at once. Press Ctrl-F after typing your command line (before pressing ENTER) and you will see what is being executed.

Create a function that does the substitution for you.
Code:
function foo=%%@if[%%2.==.,%%1,%%2]
echo %@foo[1,2] %@foo[1]
2 1

Then your alias becomes:
Code:
alias RC=RichCopy "%%1" "%%@foo[%%1,%%2]"
 
Thanks, Scott! I didn't know that aliases didn't perform short circuit evaluation.

Here is my alias and companion function that works in all of the test cases I tried (as copied from my .als and .fns files):

RichCopy="c:\Program Files (x86)\Microsoft Rich Tools\RichCopy 4.0\RichCopy.exe" %@quote[%@full[%1]] %@quote[%@if[%# == 1,%@quote[%_cwd\%@filename[%1]],%@full[%@Maybe2nd[%1,%2]]]]

Maybe2nd=%@if[%2.==.,%1,%2]
 
I think you're over complicating it.
Code:
function qfull=%@quote[%@full[%1]]
RichCopy="c:\Program Files (x86)\Microsoft Rich Tools\RichCopy 4.0\RichCopy.exe" %@qfull[%1] %@qfull[%@Maybe2nd[%1 %2]]
 
As far as I know, quoting all your file names doesn't hurt anything. So you could shorten it by removing @quote and just use quotes.
Code:
RichCopy="c:\Program Files (x86)\Microsoft Rich Tools\RichCopy 4.0\RichCopy.exe" "%@full[%1]" "%@full[%@Maybe2nd[%1 %2]]"

BTW - You will run into an issue if the file names you are using have spaces in them.
Code:
echo %@Maybe2nd[hello world.txt, foo bar.txt]
world.txt
 

Similar threads

Back
Top