我有以下shell脚本。
SCRIPT1
#!/bin/bash
foo() {
echo "foo from Script1"
}
foo1() {
echo "foo1 from Script1"
}
source script2
foo
fool
SCRIPT2
#!/bin/bash
foo() {
echo "foo from Script2"
}
foo1() {
echo "foo1 from Script2"
}
我得到以下输出:
来自Script2的foo
来自Script2的foo1
预期输出
来自Script2的foo
来自Script1的foo1
我知道source命令在这里播放了spoilsport。有没有办法将控制权恢复到Script1或任何其他替代方法来实现这一目的?
答案 0 :(得分:4)
在采购readonly
之前,您可以使用foo1
将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.
答案 1 :(得分:0)
如果你希望脚本2的源代码只影响foo的执行,一种可能性就是把它放在子shell中:
( . script2 ; foo ; )
foo1
输出:
foo from Script2
foo1 from Script1
答案 2 :(得分:0)
在声明source script2
foo1
移至
#!/bin/bash
foo() {
echo "foo from Script1"
}
source script2 #Move this line to before declaration of foo1()
foo1() {
echo "foo1 from Script1"
}
foo
foo1