Example of a simple function in a shell script

Source: Internet
Author: User

This script my_name shows how the arguments to the function are passed, and how the function returns a value of TRUE or false. Use a parameter to invoke the script, which is the name you want to use in the problem.

Shell script code

#!/bin/shyes_or_no () {  echo "is your name $*?"  While true  does    echo-n "Enter Yes or no:"    read x Case    ' $x ' in      y | YES) return 0;;      n | No  ) return 1;;      *  )      echo "Answer Yes or no"      Esac   done}echo "Original parameters is $*" If Yes_or_no "$"  Then echo "Hi $1,nice name" Else  echo "Never Mind" Fiexit 0  


Test results



when the script starts, the function yes_or_no is defined, but it is not executed first. In the IF statement, when the script executes to function yes_or_no, first replace the first parameter of the program with Zhang, and then pass it as a parameter to the function. The function will use these parameters (they are now saved in a positional parameter of $, $) and return a value to the caller. The IF structure then executes the response statement according to the return value.

If statement in the shell, if Yes_or_no returns 0, then go to branch, and if return 1, go to Else branch.

Example of a simple function in a shell script

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.