0

I have a program named go.exe, and I pass it a file name example so that it can make a log file named example_golog.txt.

The problem here is that I want to only call the executable without explicitly giving a filename or making a user have to give a file name.

My solution to this was to name a system variable called GO whose value is go.exe %~n0. What's wrong with this is instead of the %~n0 part getting the file name of the batch file that called it, my go.exe file just makes a text file called %~n0_golog.txt.

Is there any way around this so that %~n0 will do it's magic in the batch files that call it in go.exe %~n0?

EDIT:

My system variable: Name: GO Value: go %~n0

My test.bat file:

@echo on
%GO% 
pause

When I run test.bat, the %~n0 does not expand out.

So instead of test_golog.txt being made, %~n0_golog.txt is made

6
  • That argument should always expand even if it was empty from shifting. Could please show us all the relevant code. Commented Nov 14, 2016 at 19:20
  • @Squashman added some more. Any idea? Commented Nov 14, 2016 at 19:20
  • If your environment variable %GO% worked as you want it to, how would it look being used in your batch file? Commented Nov 14, 2016 at 19:21
  • 1
    I see what you are saying now. You set it as a variable before you started the batch file. Why don't you just set it in the batch file? Commented Nov 14, 2016 at 19:22
  • @lyst %GO% would be go %~n0 which would expand out to go test if the batch file that ran it is named test.bat Commented Nov 14, 2016 at 19:24

1 Answer 1

6

In your batch file, you can call it to dereference the variable.

echo %go% will report go %~n0.

call echo %go% will report go test (from a batch file named test).

You can use whatever other sets you need from there.

Sign up to request clarification or add additional context in comments.

3 Comments

This will not execute go.exe and expand the %~n0 to the batch file name. The CALL ECHO trick works because it is expanding the variables twice. But it will not expand %~n0 when removing the ECHO. You would need to put this into a FOR /F command to capture the output and then execute that macro variable.
@Squashman Thats not quite right, Call %go% will execute the content of the var Go with %~n0 expanded to the current batch file name, no need for for /f. But I agree the construct is a bit weird
@LotPings, I tested by setting set go=find.exe "%~n0" %0 and sure enough it works. I have no idea why! You never see %0 get expanded at all. Seriously confused by this one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.