- Команда EXIT – завершить работу командного процессора или текущего командного файла.
- Batch Script — Return Code
- Error Level
- Syntax
- Example
- Output
- Loops
- Looping through Command Line Arguments
- Example
- Output
- exit exit
- Синтаксис Syntax
- Параметры Parameters
- Примеры Examples
- Команда EXIT: выход из командной строки Windows или командного файла
- ERRORLEVEL это не %ERRORLEVEL%
Команда EXIT – завершить работу командного процессора или текущего командного файла.
Команда EXIT используется для завершения пакетных файлов с установкой значения переменной ERRORLEVEL или для завершения командного процессора CMD.EXE ( для выхода из командной строки), если она выполняется вне пакетного файла.
Формат командной строки:
EXIT [/B] [exitCode]
Параметры командной строки:
/B — Предписывает завершить текущий пакетный файл-сценарий вместо завершения CMD.EXE. Если выполняется вне пакетного файла-сценария, то будет завершена программа CMD.EXE
exitCode — Указывает цифровое значение. Если указан ключ /B, определяет номер для ERRORLEVEL. В случае завершения работы CMD.EXE, устанавливает код завершения процесс с данным номером.
Примеры использования команды EXIT
exit — завершить текущий сеанс CMD
Команда EXIT с параметрами используются, как правило, только в командных файлах. Например, для индикации результата выполнения с установкой значения переменной среды ERRORLEVEL
REM перейти к метке, где выполняется выход с ERRORLEVEL=0
REM перейти к метке, где выполняется выход с ERRORLEVEL=1
REM установить ERRORLEVEL равный 0 и завершить работу
REM установить ERRORLEVEL равный 1 и завершить работу
Параметр /B используется в тех случаях, когда выполняется завершение командного файла, но необходимо продолжить работу командного процессора. Например, когда командный файл 1.bat вызывает командной CALL другой командный файл 2.bat , результат выполнения которого, характеризуется значением переменной окружения ERRORLEVEL . Если в вызываемом командном файле использовать команду EXIT без параметра /B, то будет завершена работа вызываемого файла 2.bat, а также вызывающего файла 1 .bat и интерпретатора CMD.EXE, т.е вместо выхода из вызываемого файла будет полностью завершен сеанс командной строки.
Простейший пример, когда командный файл 1.bat вызывает на выполнение другой командный файл с именем 2.bat и выводит на экран значение ERRORLEVEL, установленное при выходе из вызываемого файла:
echo Batch file 2.bat executed with ERRORLEVEL = %ERRORLEVEL%
Файл 2.bat завершается командой EXIT с установкой значения ERRORLEVEL, равного 128:
При выполнении командного файла 1.bat на экран будет выведено сообщение:
Batch file 2.bat executed with ERRORLEVEL = 128
Попробуйте убрать параметр /B в команде EXIT командного файла 2.bat и оцените полученный результат.
Batch Script — Return Code
By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly.
Following are the common exit code and their description.
Error Code | Description |
---|---|
0 | Program successfully completed. |
1 | Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe. |
2 | The system cannot find the file specified. Indicates that the file cannot be found in specified location. |
3 | The system cannot find the path specified. Indicates that the specified path cannot be found. |
5 | Access is denied. Indicates that user has no access right to specified resource. |
Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action. | |
The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user’s keyboard input CTRL+C or CTRL+Break or closing command prompt window. | |
The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize. |
Error Level
The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.
By default, the way to check for the ERRORLEVEL is via the following code.
Syntax
It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file.
EXIT /B at the end of the batch file will stop execution of a batch file.
Use EXIT /B at the end of the batch file to return custom return codes.
Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers.
Let’s look at a quick example on how to check for error codes from a batch file.
Example
Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9.
Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0.
Output
In the above program, we can have the following scenarios as the output −
If the file c:\lists.txt does not exist, then nothing will be displayed in the console output.
If the variable userprofile does not exist, then nothing will be displayed in the console output.
If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt.
Loops
In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements.
S.No | Loops & Description | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | While Statement Implementation There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels. The «FOR» construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values. The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement. Following is the classic ‘for’ statement which is available in most programming languages. Looping through Command Line ArgumentsThe ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments. ExampleOutputLet’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3.
|