psi*_*mon 7 bash shell-script function
我有一个调用函数的 BASH 脚本,该函数调用其他函数:
#!/bin/bash
function foo
{
function bar
{
# do something
}
bar
}
foo
Run Code Online (Sandbox Code Playgroud)
如何bar
直接从主函数返回?这种情况是bar
处理用户输入,如果它收到否定的回答,它必须返回到主函数,否则它必须返回到foo
。
foo
用简单的return
语句返回到不是问题。对于另一个,我尝试了这个(实际上有效):
#!/bin/bash
function foo
{
function bar
{
if [negative] # abstract statement
then return 1
else return 0
fi
}
! bar && return
}
foo
Run Code Online (Sandbox Code Playgroud)
但是因为我有像foo
分布在整个项目中的功能(bar
在头文件中定义),有没有一种方法只需要修改bar
?该项目长约 2k 行,由多个文件组成,如果有解决方案,这样会容易得多。
(我知道)没有什么好的方法可以做到这一点,但如果你愿意付出代价......
您可以将代码放入您源文件中,而不是将代码放入函数中。如果函数需要参数,那么您必须使用以下方法准备它们set
:
set -- arg1 arg2 arg3
source ...
Run Code Online (Sandbox Code Playgroud)
三个文件:
测试脚本.sh
#! /bin/bash
startdir="$PWD"
echo mainscript
while true; do
echo "begin: helper loop"
source "${startdir}/func_1"
echo "end: helper loop"
break
done
echo mainscript
Run Code Online (Sandbox Code Playgroud)函数_1
echo "begin: func_1"
source "${startdir}/func_2"
echo "end: func_1"
Run Code Online (Sandbox Code Playgroud)函数_2
echo "begin: func_2"
echo break from func_2
break 100
echo "end: func_2"
Run Code Online (Sandbox Code Playgroud)结果:
> ./testscript.sh
mainscript
begin: helper loop
begin: func_1
begin: func_2
break from func_2
mainscript
Run Code Online (Sandbox Code Playgroud)