[英]In Windows shell scripting (cmd.exe) how do you assign the stdout of a program to an environment variable?
[英]How do I detect if script was CALL'ed or invoked directly, in Windows CMD.EXE shell?
我需要在script.cmd里面區分這兩種情況:
C:\> call script.cmd
C:\> script.cmd
如何確定我的 script.cmd 是直接調用的,還是在使用 CALL 的上下文中調用的?
如果重要,請撥打 Windows 7。
@echo off
set invoked=0
rem ---magic goes here---
if %invoked%==0 echo Script invoked directly.
if %invoked%==1 echo Script invoked by a CALL.
任何人都知道“魔法在這里”會檢測到已調用並設置調用=1?
目前,我看不出有什么辦法可以檢測到它,但作為一種變通方法,您始終可以強制使用哨兵。
@echo off
setlocal enableextensions
rem If "flag" is not present, use CALL command
if not "%~1"=="_flag_" goto :useCall
rem Discard "flag"
shift /1
rem Here the main code
set /a "randomExitCode=%random% %% 2"
echo [%~1] exit with code %randomExitCode%
exit /b %randomExitCode%
goto :eof
rem Retrieve a correct full reference to the current batch file
:getBatchReference returnVar
set "%~1=%~f0" & goto :eof
rem Execute
:useCall
setlocal enableextensions disabledelayedexpansion
call :getBatchReference _f0
endlocal & call "%_f0%" _flag_ %*
這將允許您使用指定的語法
script.cmd first && script.cmd second && script.cmd third
發布的代碼以隨機退出代碼結束腳本以進行測試。 當退出代碼為 0 時將繼續執行
注意:為了讓它工作,至少在 XP 中,似乎對批處理文件的call
必須是批處理文件中的最后一個代碼
檢查腳本的路徑是否在 CMDCMDLINE 變量中。 如果沒有,那么它可能被調用了。
在此示例中,我使用%CMDCMDLINE:"=/%
將引號轉換為正斜杠(FIND 命令無法搜索引號),並使用<NUL SET/P=""
回顯它,以便文件路徑(如&符號)不要破壞腳本。
<NUL SET/P="%CMDCMDLINE:"=/%" | FIND "/%~0/">NUL || (
REM Commands to perform if script was called
GOTO:EOF
)
::AND/OR
<NUL SET/P="%CMDCMDLINE:"=/%" | FIND "/%~0/">NUL && (
REM Commands to perform if script was NOT called
GOTO:EOF
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.