问题
I'm working within a batch file and I have a Perforce command to call in order to gain some user information. The command is:
p4 -Ztag -F %clientName% info
Now what I need is for the result of this command to be held in either a variable or a file (ideally the former). But for the life of me I can't figure out how to do so, can someone please help me out.
I gave the following command a try:
p4 -Ztag -F %clientName% info > %HOMEPATH%\clientName.txt
But the results were:
p4 -Ztag -F info 1>\Users\UserName\clientName.txt
With the file "clientName.txt" containing:
info
Which is incorrect.
回答1:
You always need to escape percents in a batch file -- the command line will ignore undefined environment variables, but a script will expand them into an empty string. Since these percents are for the p4
command's variable expansion you never want the shell to touch them, regardless of whether there's a local environment variable defined.
Give this a whirl:
p4 -Ztag -F %%clientName%% info>CLIENTNAME
set /p CLIENTNAME=<CLIENTNAME
With credit to:
- Escape percent in bat file
- Batch equivalent of Bash backticks
(The first line puts the value into a file called CLIENTNAME, the second line reads it from the file into an env var of the same name. For some reason set /p
doesn't work with just a direct pipe like you'd think it would; I gave up on debugging that one.)
As a side note, if you're storing this in an environment variable with the idea of passing it to another p4 command that you got from some other recipe, note that this may be redundant as most p4 commands that operate on a client will already default to the same client that p4 info
gave you. :) There are also easier ways of passing information between p4 commands than Windows env vars.
回答2:
Well debugging a batch should follow some rules.
- Run the batch in an open cmd window.
- Temporarily switch
echo on
to show the commands being executed - echo the contents of a variable to screen to see current state.
- insert pause commands at critical points to not have to scroll havily
- also temporarily disable a longer prompt message to unclutter output
- insert a prefix to variables to check (like
_
),
so you can output them to a logfile withset _>>logfile.log
- prefix commands not of interrest while debugging with a
@
@Echo on
@Echo clientName=[%clientName%]
@pause
p4 -Ztag -F %clientName% info
@pause
Don't use %HOMEPATH%
solely, either with %HOMEDRIVE%%HOMEPATH%
or %USERPROFILE%
p4 -Ztag -F %clientName% info > "%USERPROFILE%\clientName.txt"
回答3:
Thanks for the help. The following worked perfectly:
p4 -Ztag -F %%clientName%% info > "%USERPROFILE%\clientName.txt"
set /p v=<"%USERPROFILE%\clientName.txt"
来源:https://stackoverflow.com/questions/50856234/results-of-perforce-command-to-command-line-variable