如何检测是否正在获取脚本 [英] How to detect if a script is being sourced

查看:32
本文介绍了如何检测是否正在获取脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,如果它是源代码,我不希望它调用 exit.

I have a script where I do not want it to call exit if it's being sourced.

我想检查是否 $0 == bash 但是如果脚本来自另一个脚本,或者用户从不同的 shell 中获取它,比如 ksh,这就会出现问题>.

I thought of checking if $0 == bash but this has problems if the script is sourced from another script, or if the user sources it from a different shell like ksh.

是否有一种可靠的方法来检测脚本是否被获取?

Is there a reliable way of detecting if a script is being sourced?

推荐答案

这似乎可以在 Bash 和 Korn 之间移植:

This seems to be portable between Bash and Korn:

[[ $_ != $0 ]] && echo "Script is being sourced" || echo "Script is a subshell"

与此类似的行或类似于 pathname="$_" 的赋值(带有稍后的测试和操作)必须在脚本的第一行或shebang 之后的行(如果使用,应该用于 ksh 以便在大多数情况下工作).

A line similar to this or an assignment like pathname="$_" (with a later test and action) must be on the first line of the script or on the line after the shebang (which, if used, should be for ksh in order for it to work under the most circumstances).

这篇关于如何检测是否正在获取脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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