shell script learning function _ _5

learning target:

Shell scripting function uses

 

to sum up:

Similarly 1- C language function and use. Direct function calls to write the function name and parameter passing; function return value can borrow $ handle?.

2- shell also have local variables and global variables. Local variables plus key local , not global variables are added.

 

 

text

1- The basic syntax

a- basic function Syntax: return value, the return value None

/*1- 不关心返回值*/
#函数定义
func() 
{
   do something
}

#函数调用。函数调用可以传入参数,利用位置变量进行处理
func param



/*2- 利用返回值*/
#函数定义
func() 
{
   do something
   return xxx
}

#函数调用。函数调用可以传入参数,处理利用$?,还可以单独定义一个变量进行处理
func param
#打印函数返回值
echo "\$?=$?"

b- local, global variables

Local variables plus key local , not global variables are added. Understood in conjunction with the examples that follow

func()
{
    #全局变量g_para;局部变量l_para
    g_para=$1
    local l_para=$2
}

 

Example 2-

Checking whether the user exists I-

Wc regarding usage Reference: https://www.cnblogs.com/cloudPython/p/4893221.html

For who | grep "^ $ 1" | wc -l command to check the number of users, not exactly match the input can be filtered through grep ( looking at grep filter usage ).

#!/bin/bash
check_user()
{
	check_cnt=`who |grep "^$1" |wc -l `
	if [ $check_cnt -eq 1 ]
	then
		return 0
	else
		return 1
	fi
}

while true
do
	echo -n "Please Input username:"
	read username
	check_user $username	
	if [ $? -eq 0 ]
	then
		echo "$username online"
	else
		echo "$username not online"
	fi
done

II- global variables, local variables exercises

Calling the function func (), in the functions that the parameters are assigned to a first global variables and local variables g_para l_para. Printing local and global variables outside the function thereof. You can see global variables can print to local variables can not print.

script:

#!/bin/bash
func()
{
	g_para=$1
	local l_param=$1
	echo "\$1=$1"
	echo "\$2=$2"
	return 12
}


echo "func begain"
func hello world
echo "\$?=$?"
echo "g_para=$g_para"
echo "l_local=$l_local"
echo "func end"

result:

func begain
$1=hello
$2=world
$?=12
g_para=hello
l_local=
func end

 

Published 38 original articles · won praise 5 · Views 5639

Guess you like

Origin blog.csdn.net/u010743406/article/details/104304579