如何从函数中退出批处理文件? [英] How can I exit a batch file from within a function?

查看:57
本文介绍了如何从函数中退出批处理文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个用于检查目录的简单函数:

I have a simple function written to check for directories:

:direxist
if not exist %~1 (
    echo %~1 could not be found, check to make sure your location is correct.
    goto:end
    ) else (
    echo %~1 is a real directory
    goto:eof
    )

:end写为

:end
endlocal

我不明白为什么在调用goto:end之后程序不会停止.我还有另一个使用相同方法来停止程序的函数,它运行正常.

I don't understand why the program would not stop after goto:end has been called. I have another function that uses the same method to stop the program and it work fine.

:PRINT_USAGE
echo Usage:
echo ------
echo <file usage information>
goto:end

在这种情况下,程序在调用:end;之后停止.为什么在:direxist中不起作用?谢谢您的帮助!

In this instance, the program is stopped after calling :end; why would this not work in :direxist? Thank you for your help!

推荐答案

我想您在这里混合了 call goto 语句.

I suppose you are mixing call and goto statements here.

批处理文件中的标签可以与 call goto 一起使用,但是行为不同.
如果您调用这样的 function ,则它将在函数到达文件末尾或显式的 exit/b goto结束时返回:eof (例如您的 goto:end ).

A label in a batch file can be used with a call or a goto, but the behaviour is different.
If you call such a function it will return when the function reached the end of the file or an explicit exit /b or goto :eof (like your goto :end).

因此,如果您将标签用作功能,则无法取消批次.

Therefore you can't cancel your batch if you use a label as a function.

但是,转到到标签时,不会返回给调用者.

However, goto to a label, will not return to the caller.

使用synatx错误:

但是还有一种方法可以从函数中退出批处理.
您可以创建语法错误,这将强制批处理停止.
但这具有副作用,即不会删除本地(setlocal)变量.

But there is also a way to exit the batch from a function.
You can create a syntax error, this forces the batch to stop.
But it has the side effect, that the local (setlocal) variables will not be removed.

@echo off
call :label hello
call :label stop
echo Never returns
exit /b

:label
echo %1
if "%1"=="stop" goto :halt
exit /b

:halt
call :haltHelper 2> nul

:haltHelper
() 
exit /b

使用CTRL-C:

创建类似于CTRL-C错误代码的错误代码也会停止批处理.
退出后,setlocal状态为 clean
请参见@dbenham的答案从函数内部退出批处理脚本

Creating an errorcode similar to the CTRL-C errorcode stops also the batch processing.
After the exit, the setlocal state is clean!
See @dbenham's answer Exit batch script from inside a function

使用高级异常处理:

这是最强大的解决方案,因为它能够删除任意数量的堆栈级别,它可用于仅退出当前批处理文件并显示堆栈跟踪.
它使用这样的事实:没有参数的(goto)从堆栈中删除了一个元素.
请参见 Windows批处理是否支持异常处理?

This is the most powerful solutions, as it's able to remove an arbitrary amount of stack levels, it can be used to exit only the current batch file and also to show the stack trace.
It uses the fact, that (goto), without arguments, removes one element from the stack.
See Does Windows batch support exception handling?

这篇关于如何从函数中退出批处理文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆