shell script function

Linux shell allows user-defined functions, which can then be called at will in shell scripts.

The definition format of functions in the shell is as follows:

[ function ] funname [()]
{
    action;
    [return int;]
}

illustrate:

  • 1. Function fun() can be defined, or fun() can be defined directly without any parameters.
  • 2. Parameter return, you can add: return to display, if not, the result of running the last command will be used as the return value.

example

funWithReturn(){
    echo "这个函数会对输入的两个数字进行相加运算..."
    echo "输入第一个数字: "
    read aNum
    echo "输入第二个数字: "
    read anotherNum
    echo "两个数字分别为 $aNum 和 $anotherNum !"
    return $(($aNum+$anotherNum))
}
funWithReturn
echo "输入的两个数字之和为 $? !"

The function return value is obtained through $? after calling the function.

Note: All functions must be defined before use. This means that the function must be placed at the beginning of the script and cannot be used until the shell interpreter first discovers it. Calling a function simply uses its function name.

Guess you like

Origin blog.csdn.net/zengliguang/article/details/135351896