1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > linux变量接收命令返回值 Linux Shell教程(一)

linux变量接收命令返回值 Linux Shell教程(一)

时间:2022-03-08 22:48:17

相关推荐

linux变量接收命令返回值 Linux Shell教程(一)

函数返回值

函数返回值,可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。

函数返回值在调用该函数后通过 $? 来获得。

范例1

来看一个带有return语句的函数:

#!/bin/bash

funWithReturn(){

echo "The function is to get the sum of two numbers..."

echo -n "Input first number: "

read aNum

echo -n "Input another number: "

read anotherNum

echo "The two numbers are $aNum and $anotherNum !"

return $(($aNum+$anotherNum))

}

funWithReturn

# Capture value returnd by last command

ret=$?

echo "The sum of two numbers is $ret !"

运行结果:

The function is to get the sum of two numbers...

Input first number: 25

Input another number: 50

The two numbers are 25 and 50 !

The sum of two numbers is 75 !

Shell 函数返回值只能是整数,一般用来表示函数执行成功与否,0表示成功,其他值表示失败。如果 return 其他数据,比如一个字符串,往往会得到错误提示:“numeric argument required”。

注:如果一定要让函数返回字符串,那么可以先定义一个变量,用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值。

1、编写并运行范例脚本。

2、编写shell脚本,定义一个函数计算a+b,主程序中输出函数的返回值。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。