为什么这个shell脚本终端 return 语句是错误的

如题所述

http://zhidao.baidu.com/question/2010919334866095868

这是一个Linux shell的问题。 就bash而言, return命令只能用在函数中,不能直接用在脚本中(不能直接用在脚本终端),当脚本用source a1.sh(或者 . a1.sh)执行时,可以用在脚本中。( return: can only`return' from a function or sourced script)

下面的内容,摘自<<实用Linux Shell编程>>,刚刚上市的书,写得不错,各卖书网有卖,建议买一本。供参考:

内置命令return用于从函数中返回, ..., return命令在函数中不是必须的,函数被调用时,函数内的命令执行完成后自然会返回到调用它的地方(一般是返回到主程序)。如果某函数中有return命令,执行到return时就返回。如果return在函数中不是最后一条命令,那么return后面的其他命令不再执行。
......

注意return命令不能直接用在脚本的主程序里,请看下面的例子:
$ cat fun_return_2.sh
#!/bin/bash
echo "return_2_1"
return
echo "return_2_2"

如果直接运行脚本,会遇到错误提示:
$ ./fun_return_2.sh
return_2_1
./fun_return_2.sh: line 3: return: can only`return' from a function or sourced script
return_2_2

用source命令或者点命令来运行该脚本,就没问题:
$ source fun_return_2.sh
return_2_1

先执行脚本fun_return_2.sh的第一条echo命令,显示return_2_1,然后执行return,脚本结束,第二条echo命令不被执行。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-07-29
从函数或者源脚本`返回'
出错信息说明很清楚了
从函数里 return 很好理解
从源脚本‘返回’,要看英文原文才好理解:can only `return' from a function or sourced script
注意是 sourced script
也就是用 source 或者 . 命令加载的脚本
所以你这个脚本在别的地方 source 或者 . 进来就不错了:
source test.sh
或者
. test.sh
相似回答