本系列适合Linux初学者,属于Linux入门级教程,主要介绍了Shell的分类、语法格式以及脚本的使用和编写格式等。 不断更新中,是Shell学习的必读经典教程。 Linux Shell系列教程之(一)Shell简介 Linux Shell系列教程之(二)第一个Shell脚本 Linux Shell系列教程之(三)Shell变量 Linux…
March 5, 2018
Shell: 获取函数返回值, Returning value from called function in a shell script
shell函数不能直接返回字符串,用以下三种方式代替!
A Bash function can’t return a string directly like you want it to. You can do three things:
- Echo a string
- Return an exit status, which is a number, not a string
- Share a variable
This is also true for some other shells.

Here’s how to do each of those options:
1. Echo strings
lockdir="somedir" testlock(){ retval="" if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo >&2 "successfully acquired lock: $lockdir" retval="true" else echo >&2 "cannot acquire lock, giving up on $lockdir" retval="false" fi echo "$retval" } retval=$( testlock ) if [ "$retval" == "true" ] then echo "directory not created" else echo "directory already created" fi
2. Return exit status
lockdir="somedir" testlock(){ if mkdir "$lockdir" then # Directory did not exist, but was created successfully echo >&2 "successfully acquired lock: $lockdir" retval=0 else echo >&2 "cannot acquire lock, giving up on $lockdir" retval=1 fi return "$retval" } testlock retval=$? if [ "$retval" == 0 ] then echo "directory not created" else echo "directory already created" fi
3. Share variable
lockdir="somedir" retval=-1 testlock(){ if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo >&2 "successfully acquired lock: $lockdir" retval=0 else echo >&2 "cannot acquire lock, giving up on $lockdir" retval=1 fi } testlock if [ "$retval" == 0 ] then echo "directory not created" else echo "directory already created" fi
更多参看:详细介绍Linux shell脚本系列基础学习(列表)
本文:Shell: 获取函数返回值, Returning value from called function in a shell script
One Comment