About the return values of functions in Shell, shell return values

Source: Internet
Author: User

About the return values of functions in Shell, shell return values
#! /Bin/sh
Sum ()
{
Echo $($1 + $2 ))
Return $($1-$2 ))
}
Sum $1 $2
C =$ (sum $1 $2)
Echo $?
Echo $ c
Run the command:./bashTest 11 1.
The running result is:
12 -- result of sum $1 $2
10 -- echo $? Because the return value is 10.
12 -- echo $ c result, the value is 12, so c will not be attached with the return value, echo $ c calls the sum function, so print 12

Our understanding of the return values in shell is biased. The return values in shell generally refer to the return values after the command is executed. Generally, if the command is executed successfully, 0 is returned. If the command fails to be executed, 1 is returned. After the command is executed, echo $? Check the return value. In this example, because the function has a return statement, the function defines a return value. You can use echo $? Check the returned value. The value of c = $ (sum $1 $2) is not equal to the value of return, which means that the shell does not define a function in C, call the return value as c = abs (I, j.
Someone said this:
Basically, it means that the function in shell does not assign the return value of the function to a variable like other languages?
For example
C = sum_test $1 $2
Echo $ c nickname: hxl time: 10:34:00 reply hxl
No .... Nickname: lkk2003rty time: 2010-06-09 11:27:00
############### The above is from the http://blog.163.com/wangfeng2500@126/blog/static/44780245201062865644141 /##################
Correct method:Function plus (){
Read-p "input number1:" number1
Read-p "input number2:" number2
# Echo $ ($ number1 + $ number2) # The two sets of parentheses mean arithmetic operations.
Echo 'expr $ number1 + $ number2'
}
Res = $ (plus)
Echo "plus result is $ res"

Use echo, call and obtain with res = $ (plus)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.