Errorlevel
is a system variable in Bash that contains the status or error code of the last command execution.
If it returns 0, the command is successful. If it returns non-zero, the command failed with an error, returns an exit(error) code.
For example,
@echo off
REM error level failed and succesfull case
ls
echo %errorlevel%
dir
echo %errorlevel%
We have used two commands in the batch script:
ls
is not a valid command in DOS and throws an error “ls command is not internal or external”, so errorlevel returns9009
.dir
is a valid command and executes successfully, so it returns errorlevel as0
.
Batch IF Conditional checking Error Level Example
You can use the errorlevel
variable in conditional expressions to execute conditional branches based on error or successful command execution.
To check the errorlevel
, use the equ
operator to check if the exit code is zero for successful operation.
@echo off
ls
echo %errorlevel%
if %errorlevel% equ 0 (
echo Success.
) else (
echo Failed. Errorlevel: %errorlevel%.
)
Batch File Error Codes
Errorlevel always returns an error code in a batch file. It is also called an exit code.
error code | Description |
---|---|
0 | Successful |
1 | Function name is invalid |
2 | File not found |
3 | file path not found |
5 | Permission issue and Access is denied |
6 | error in executon non executable command |
7 | Invalid file descriptor |
8 | Not enough permissions to access the file |
9 | Environment variables not configured |
9007 | Command is not internal and external command |
Errorlevel and ERRORLEVEL are the same.
These variables are not changed by the user, not recommended.