Detailed explanation of Shell functions (function definition, function call, parameter variables)

The essence of a Shell function is a piece of script code that can be reused. This code has been written in advance and placed at a designated location. It can be called directly when used.

Functions in Shell  are similar to functions in other programming languages ​​such as C++ , Java , Python , C#, etc., but differ in syntax details.

The syntax format of Shell function definition is as follows:

function name() {
    statements
    [return value]
}

 Description of each part:

  • functionis a keyword in Shell, specifically used to define functions
  • nameis the function name
  • statementsis the code to be executed by the function, that is, a set of statements
  • return valueIndicates the return value of the function, where return is the Shell keyword, specifically used to return a value in the function; this part can be written or not.

The enclosed { }part is called the function body. Calling a function actually executes the code in the function body. 

Below is an example of a simple function.

function hello() {
  echo "Hello $1"
}

In the above code, the function body $1represents the first parameter when the function is called. When calling, just write the function name directly, and the parameters follow the function name.

Simplified writing of function definition


If you find it troublesome, you don’t need to write the function keyword when defining the function: 

name() {
    statements
    [return value]
}

 If you write the function keyword, you can also omit the parentheses after the function name:

function name {
    statements
    [return value]
}

I suggest using standard writing methods, so that you can "know the meaning by seeing the name" and understand it at a glance. 

function call


When calling the Shell function, you can pass parameters to it or not. If no parameters are passed, just give the function name directly: 

name

 If parameters are passed, multiple parameters are separated by spaces:

name param1 param2 param3

Regardless of the form, parentheses are not required after the function name.

Unlike other programming languages, the Shell function cannot specify parameters when it is defined, but it can pass parameters when it is called , and it will receive whatever parameters are passed to it.

Shell also does not limit the order of definition and call. You can put the definition before the call, or vice versa, put the definition after the call.

 

 

parameter variable


Parameter variables can be used within the function body to obtain function parameters. The parameter variables of the function are consistent with the script parameter variables.

  • $1~ $9: The first to ninth parameters of the function.
  • $0: The name of the script where the function is located.
  • $#: The total number of parameters of the function.
  • $@: All parameters of the function, separated by spaces.
  • $*: All parameters of the function. The parameters $IFSare separated by the first character of the variable value. The default is a space, but it can be customized.

If the function has more than 9 parameters, the 10th parameter can be ${10}referenced in the form of , and so on.

Below is an example script test.sh.

#!/bin/bash
# test.sh

function alice {
  echo "alice: $@"
  echo "$0: $1 $2 $3 $4"
  echo "$# arguments"

}

alice in wonderland

Run the script and the results are as follows.

$ bash test.sh
alice: in wonderland
test.sh: in wonderland
2 arguments

In the above example, since the function aliceonly has the first and second parameters, the third and fourth parameters are empty.

Below is an example of a log function.

function log_msg {
  echo "[`date '+ %F %T'` ]: $@"
}

How to use it is as follows.

$ log_msg "This is sample log message"
[ 2018-08-16 19:56:34 ]: This is sample log message

 

Example demonstration


1) Define a function to output the address of the Shell tutorial: 

#!/bin/bash

#函数定义
function url(){
    echo "http://c.biancheng.net/shell/"
}

#函数调用
url

 Running result:
http://c.biancheng.net/shell/

You can put the call in front of the definition, that is, write it in the following form:

#!/bin/bash
#函数调用
url

#函数定义
function url(){
    echo "http://c.biancheng.net/shell/"
}

 2) Define a function to calculate the sum of all parameters:

#!/bin/bash
function getsum(){
    local sum=0
    for n in $@
    do
         ((sum+=n))
    done
    return $sum
}
getsum 10 20 55 15  #调用函数并传递参数
echo $?

Running result:
100

$@represents all parameters of the function and $?represents the exit status (return value) of the function . Regarding how to obtain the parameters of the function, we will explain in detail in the section " Shell Function Parameters ".

Here we use the return keyword to return the $?sum of all numbers, and use Languages ​​vary greatly, as we'll discuss in Shell Function Return Values .

Sample system initialization


This script is used for configuration work related to newly installed Linux, such as changing the default yum source, optimizing the system kernel, stopping some unnecessary system services, etc. This script is especially suitable for a large number of newly installed CentOS series servers. Applies to Centos7 

shell>vim cenots_7_system_init.sh
#!/bin/bash
# Filename:    centos7-init.sh
# Author:      test
 
#判断是否为root用户
if [ `whoami` != "root" ];then
echo " only root can run it"
exit 1
fi
 
#执行前提示
echo -e "\033[31m 这是centos7系统初始化脚本,将更新系统内核至最新版本,请慎重运行!\033[0m" 
read -s -n1 -p "Press any key to continue or ctrl+C to cancel"
echo "Your inputs: $REPLY"
 
#1.定义配置yum源的函数
yum_config(){
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
yum clean all && yum makecache
}
 
#2.定义配置NTP的函数
ntp_config(){
yum –y install chrony
systemctl start chronyd && systemctl enable chronyd
timedatectl set-timezone Asia/Shanghai && timedatectl set-ntp yes
}
 
#3.定义关闭防火墙的函数
close_firewalld(){
systemctl stop firewalld.service &> /dev/null 
systemctl disable firewalld.service &> /dev/null
}
 
#4.定义关闭selinux的函数
close_selinux(){
setenforce 0
sed -i 's/enforcing/disabled/g' /etc/selinux/config
}
 
#5.定义安装常用工具的函数
yum_tools(){
yum install –y vim wget curl curl-devel bash-completion lsof iotop iostat unzip bzip2 bzip2-devel
yum install –y gcc gcc-c++ make cmake autoconf openssl-devel openssl-perl net-tools
source /usr/share/bash-completion/bash_completion
}
 
#6.定义升级最新内核的函数
update_kernel (){
rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-3.el7.elrepo.noarch.rpm
yum --enablerepo=elrepo-kernel install -y kernel-ml
grub2-set-default 0
grub2-mkconfig -o /boot/grub2/grub.cfg
}
 
#执行脚本
main(){
    yum_config
    ntp_config
    close_firewalld
    close_selinux
    yum_tools
    update_kernel
}‘
main

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/132807013