批处理脚本 - 返回代码
返回码是程序执行时返回的代码。如果命令行成功,它应该返回零;如果不成功,它应该返回非零。如果测试失败,一个非零值表示错误号,用户可以尝试通过导航到错误消息来解决它。
测试也可能返回退出代码。程序或实用程序的退出代码通常在完成或终止时出现。
下面的列表包括程序可能返回的一些非零退出代码(及其各自的错误)Error Code Description 0 Successful completion of the program. 1 This error indicates that the Windows command prompt has attempted to execute an unrecognized action 2 An error indicating that the file could not be found in the specified location 3 An error message indicated that the specified path could not be found. 5 An indication that the user is not authorized to access the resource 90090×2331 This error occurs when you misspell the command, application name, or path when configuring an Action. 2212254950xC0000017-1073741801 The error message tells you that Windows has run out of memory. 32212257860xC000013A-1073741510 This indicates that the user terminated the application 32212257940xC0000142-1073741502 The message indicating that the application was launched on a desktop to which the current user doesn’t have access
批处理文件错误级别:
%ERRORLEVEL% 是一个环境变量,包含批处理文件中的最后一个错误级别或返回代码——即最后执行的命令的最后一个错误代码。可以使用%ERRORLEVEL%变量检查错误级别,如下所示:
IF %ERRORLEVEL% NEQ 0 (
DO_Something
)
从批处理文件返回错误代码的常用方法是使用命令EXIT /B %ERRORLEVEL%。
对于自定义返回代码,请使用EXIT /B
例子:
在下面的示例中,如果满足条件,则脚本将以退出代码 0 终止。如果不满足条件,则退出代码将为 1。
if [[ "$(whoami)" != root ]]; then
echo "Not root user."
exit 1
fi
echo "root user"
exit 0
输出:
循环:
在决策一章中依次颁布了声明。或者,批处理脚本也可用于更改程序逻辑中的控制流。然后将这些语句组织成流控制语句。Serial No Loops Description 1 While Statement Implementation There is no direct while statement in Batch Script, although labels and an if statement can be used to implement this loop. 2 For Statement – List Implementations Batch files can loop using the “FOR” construct. In order to work with a list of values, the ‘for’ statement requires the following construct. 3 Looping through Ranges ‘For’ statements can also move through ranges of values. A general version is presented below. 4 Classic for Loop Implementation It has the classic ‘for’ statement found in many programming languages. 5 Break Statement Implementation Within any programming language, the break statement is used to alter the flow of control inside a loop. As part of looping constructs, the break statement causes the innermost enclosing loop to terminate immediately
循环命令行参数
要检查命令行参数,可以使用 for 语句。这是一个如何使用“for”语句循环命令行参数的示例。
for ((c=1; c<=7; c++))
do
echo "Welcome $c times"
done
输出: