考虑foo.sh:
#!/bin/bash
function foo() {
source another.sh
echo "This shouldn't be executed. Return code: $?"
return 0
}
foo
echo "Return code: $?"
然后是另一个.sh:
echo "Inside another.sh"
return 1
运行./foo.sh
打印:
Inside another.sh
This shouldn't be executed. Return code: 1
Return code: 0
是否有另一种方法将源文件包含到另一个中,以便return
命令从函数封闭包含命令而不是从命令本身返回?
答案 0 :(得分:1)
一个选项是在foo.sh中传播返回代码:
source another.sh || return $?
然后:
$ ./foo.sh
Inside another.sh
Return code: 1
或者,退出另一个.sh:
中的整个脚本exit 1
然后:
$ ./foo.sh
Inside another.sh
$ echo $?
1