您如何返回到源 bash 脚本? [英] How do you return to a sourced bash script?

查看:25
本文介绍了您如何返回到源 bash 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用来源";在 bash 脚本中,如下所示:

I use "source" inside a bash script, as follows:

#!/bin/bash
source someneatscriptthatendsprematurely.sh

我想退出 someneatscriptthatendsprematurely.sh 脚本,而不退出主脚本.

I would like to exit from the someneatscriptthatendsprematurely.sh script, without exiting from the main script.

任何帮助表示赞赏!

推荐答案

你需要return语句:

返回 [n]

使函数以 n 指定的返回值退出.如果省略n,则返回状态为函数体中执行的最后一条命令的状态.如果在函数外部使用,但在 . (source) 命令执行脚本期间,它会导致 shell 停止执行该脚本并返回 n 或退出在脚本中执行的最后一个命令的状态作为脚本的退出状态.如果在函数外部而不是在 . 执行脚本期间使用,则返回状态为 false.任何与 RETURN 陷阱相关的命令都会在函数或脚本之后继续执行之前执行.

Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body. If used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. If used outside a function and not during execution of a script by ., the return status is false. Any command associated with the RETURN trap is executed before execution resumes after the function or script.

您可以通过以下两个脚本看到这一点:

You can see this in action with the following two scripts:

script1.sh:
    . script2.sh
    echo hello again

script2.sh:
    echo hello
    return
    echo goodbye

当你运行 script1.sh 时,你会看到:

When you run script1.sh, you see:

hello
hello again

这篇关于您如何返回到源 bash 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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