gpt4 book ai didi

linux - 从 shell 脚本中的 source 命令退出

转载 作者:太空狗 更新时间:2023-10-29 11:45:08 27 4
gpt4 key购买 nike

我有以下 shell 脚本。

脚本1

#!/bin/bash
foo() {
echo "foo from Script1"
}
foo1() {
echo "foo1 from Script1"
}
source script2
foo
fool

脚本2

#!/bin/bash
foo() {
echo "foo from Script2"
}
foo1() {
echo "foo1 from Script2"
}

我得到以下输出:

foo from Script2

foo1 from Script2

预期输出是

foo from Script2

foo1 from Script1

我知道 source 命令在这里玩弄恶作剧。有什么方法可以将控制权交还给 Script1 或任何其他替代方法来实现此目的?

最佳答案

您可以使用 readonlyfoo1 定义为只读,然后再获取 script2

#!/bin/bash
foo() {
echo "foo from Script1"
}
foo1() {
echo "foo1 from Script1"
}
readonly -f foo1 # This would define foo1 as readonly
# and it wouldn't change upon sourcing script2
source script2
foo
foo1

在执行 script1 时,您会看到:

script2: line 7: foo1: readonly function
foo from Script2
foo1 from Script1

如果您想要错误(输出中的第一行不被打印),将错误流重定向到 /dev/null,即通过说 bash script1 2> 调用您的脚本/dev/null.


文档:

$ help readonly
readonly: readonly [-aAf] [name[=value] ...] or readonly -p
Mark shell variables as unchangeable.

Mark each NAME as read-only; the values of these NAMEs may not be
changed by subsequent assignment. If VALUE is supplied, assign VALUE
before marking as read-only.

Options:
-a refer to indexed array variables
-A refer to associative array variables
-f refer to shell functions
-p display a list of all readonly variables and functions

An argument of `--' disables further option processing.

Exit Status:
Returns success unless an invalid option is given or NAME is invalid.

关于linux - 从 shell 脚本中的 source 命令退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344693/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com