一、if语句

1.单分支格式

if [ 条件判断式 ]; then
    当条件判断成立时,执行的命令内容
fi                 
if [ 条件判断式 ]
then
    当条件判断成立时,执行的命令内容
fi  

2.双分支格式

if [ 条件判断式 ]; then
    当条件判断成立时,执行的命令内容
else
    当条件判断不成立时,执行的命令内容
fi 

3.多分支格式

if [ 条件判断式 ]; then
    当条件判断成立时,执行的命令内容
elif [ 条件判断式2 ]; then
    当条件判断2成立时,执行的命令内容
else
    当上面条件判断都不成立时,执行的命令内容
fi 

4.实例测试

通过ping测试局域网内,主机是否在线

dtt@debian:~/shell$ cat if_test.sh 
#!/bin/bash

ip=192.168.2.111

if ping -c1 $ip &>/dev/null
then
	echo "$ip is up"
else
	echo "$ip is down"
fi

dtt@debian:~/shell$ chmod 755 if_test.sh 
dtt@debian:~/shell$ ./if_test.sh 
192.168.2.111 is up
dtt@debian:~/shell$ 

二、for循环

1.格式

for  变量名  in  取值列表
do
	执行命令内容
done

2.实例测试

通过ping测试局域网内,192.168.2网段全部主机是否在线,并将是否在线结果分开存储到文件。

for_test.sh

#!/bin/bash
ip1="192.168.2."

for n in {1..254}
do
	ip2=$(echo $n)
	ip=$ip1$ip2

	# echo $ip
	
	if ping -c1 $ip &>/dev/null
	then
		echo "$ip is up"
		echo "$ip" &>> host_up.txt
	else
		echo "$ip is down"
		echo "$ip" &>> host_down.txt
	fi
done

三、while循环

1.格式

while   [ 条件判断式 ]
do
  当上述条件判断式为真时,执行命令语句
done   

2.实例测试

dtt@debian:~$ cat while_test.sh 
#!/bin/bash

n=1
sum=0

while [ $n -lt 5 ]
do
	#echo $n
	let sum+=n
	let n+=1
done

echo "sum=$sum"
dtt@debian:~$ chmod 755 while_test.sh 
dtt@debian:~$ ./while_test.sh 
sum=10
dtt@debian:~$ 

continue表示当满足条件时跳出本次循环,继续后续循环执行。

break表示当满足条件时直接结束本次循环。

四、函数

1.函数格式

function 函数名(){
    函数体
    return 返回值
}
function 函数名{
    函数体
    return 返回值
}
函数名(){
    函数体
    return 返回值
}

2.实例测试

判断文件夹中是否存在ip.txt文件

dtt@debian:~/shell$ cat function_test.sh 
#!/bin/bash

file="ip.txt"
#定义函数
function test(){
	for file_name in `ls`
	do
		# echo $file_name

		if [ "$file_name" == "$file" ];then
			echo "$file文件存在"
		fi
	done
}

#执行函数
test

dtt@debian:~/shell$ chmod 755 function_test.sh 
dtt@debian:~/shell$ ./function_test.sh 
ip.txt文件存在
dtt@debian:~/shell$ 

3.有关函数执行的基础概念

  • shell函数必须先定义,再执行,shell脚本自上而下加载。

  • 执行shell函数,直接写函数名字即可,无需添加其他内容。

  • 函数体内定义的变量,称为局部变量,使用local关键字,定义局部变量。

  • 函数体内需要添加return语句,作用是退出函数,且赋予返回值给调用该函数的程序,也就是shell脚本(在shell脚本中,定义并使用函数,shell脚本执行结束后,通过$?获取其返回值)。

  • return语句和exit不同:

    return是结束函数的执行,返回一个退出值或返回值。

    exit是结束shell环境,返回一个退出值或返回值给当前的shell。

  • 函数如果单独写入一个文件里面,需要使用source读取。

4.函数传参数

函数定义和执行,很多都是分开在不同的文件中,函数写在一个文件中,只定义不执行,另外一个脚本,读取该函数文件,且加载该函数。

下面测试,func2.sh调用加载func1.sh文件,并向func1.sh内的get函数传4个参数


dtt@debian:~/shell$ cat func1.sh 
#!/bin/bash


get(){
	echo "传入的参数个数共$#个"
	
	for arg in $@
	do
		echo "$arg"
	done
}

dtt@debian:~/shell$ cat func2.sh 
#!/bin/bash


# 条件测试,加载函数
[ -f /home/dtt/shell/func1.sh ] && source /home/dtt/shell/func1.sh || exit

# 执行函数
get $1 $2 $3 $4

dtt@debian:~/shell$ bash func2.sh 10 20 30 40
传入的参数个数共4个
10
20
30
40
dtt@debian:~/shell$