Shell Basics (ix) function

Source: Internet
Author: User

function allows us to divide a complex function into several modules, which makes the program structure clearer and the code reuse more efficient. Like other programming languages, the Shell supports functions as well. The Shell function must first be defined and then used
1. The Shell functions are defined in the following format:

function return value, you can explicitly increment the return statement, if not added, the last command will run the result as the return value.

The Shell function return value can only be an integer, which is generally used to indicate success or failure of the function, 0 for success, and other values to fail.
If you return other data, such as a string, you will often get an error message: "Numeric argument required".
The calling function only needs to give the function name, and no parentheses are required.
The test examples are as follows:

#!/bin/sh#author:lottu#copyright (c) li0924.comfunction Lottu () {echo "HI Lottu" read-p "Please input your name:" Name echo "HI ${name}"}lottu                       #调用函数echo $?                 #打印函数执行结果执行结果如下:./fun01.shhi lottuplease Input your Name:li0924hi li09240

2. Delete a function
As with variables, the delete function can also use the unset command, but add the. f option as follows:

unset. F function_name

If you want to call a function directly from the terminal, you can define the function in the. profile file in the home directory so that you can immediately invoke the function name at the command prompt after each login.

3. Function parameters
In the shell, arguments can be passed to a function when it is called. Inside the function body, the value of the parameter is obtained in the form of a $n, for example, $ $ for the first argument, and $ for the second argument.
Note that the $ $ cannot get the tenth parameter, and the tenth parameter requires ${10}. When n>=10, you need to use ${n} to get the parameters. Dressing theory.

Shell Basics (ix) function

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.