标签:shell
第1章 while循环语句在编程语言中,while循环是一种控制流程的陈述,利用一个返回结果为布林值的表达式,当这个表达式的返回值为真时,则反复执行循环的条件,若表达式的返回值为假,则不在执行循环的条件
while 条件
do
命令
done
[root@nfs01 tmp]# cat test.sh
#!/bin/bash
##############################################################
# File Name: test.sh
# Version: V1.0
# Author: da ya
# Organization: 850144102@qq.com
# Created Time : 2018-03-24 19:48:06
# Description:
##############################################################
while true
do
echo "ok" | nc -l 81
done
[root@nfs01 tmp]# sh test.sh
GET / HTTP/1.1
User-Agent: curl/7.29.0
Host: 10.0.0.31:81
Accept: */*
GET / HTTP/1.1
User-Agent: curl/7.29.0
Host: 10.0.0.31:81
Accept: */*
[root@nfs01 tmp]# cat test.sh
#!/bin/bash
while true 使返回值总是为真,所以会一直循环
do
uptime
sleep 1
done
[root@nfs01 tmp]# sh test.sh
19:48:45 up 2 days, 4:12, 4 users, load average: 0.08, 0.04, 0.05
19:48:46 up 2 days, 4:12, 4 users, load average: 0.08, 0.04, 0.05
19:48:47 up 2 days, 4:12, 4 users, load average: 0.08, 0.04, 0.05
19:48:48 up 2 days, 4:12, 4 users, load average: 0.07, 0.04, 0.05
^C
补充定时任务功能,执行小于一秒的任务
循环执行某些操作,例如水果菜单
while read i
do
echo "$i"
done < /etc/hosts
[root@nfs01 scripts]# sh test.sh
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.16.200 mirrors.aliyun.com
cat /etc/hosts|while read i
do
echo "$i"
done
exec < /etc/hosts
while read i
do
echo "$i"
done
获取一行中每个单词
while read i
do
echo "$i"
for w in $i
do
echo "$w"
done
done < /etc/hosts
for i in {1..5}
do
if [ "$i" -eq 2 ];then
break
fi
echo "$i"
done
echo OK
[root@nfs01 scripts]# sh test.sh
1
OK
for i in {1..5}
do
if [ "$i" -eq 2 ];then
continue
fi
echo "$i"
done
echo OK
[root@nfs01 scripts]# sh test.sh
1
3
4
5
OK
for i in {1..5}
do
if [ "$i" -eq 2 ];then
exit
fi
echo "$i"
done
echo OK
[root@nfs01 scripts]# sh test.sh
1
简答的说:数组就是多个变量的组合
[root@nfs01 scripts]# name=(jiang bo yang)
[root@nfs01 scripts]# echo ${name[1]}
bo
[root@nfs01 scripts]# echo ${name[2]}
yang
[root@nfs01 scripts]# unset name[1]
[root@nfs01 scripts]# echo ${name[1]}
[root@nfs01 scripts]# echo ${name[*]}
jiang yang
[root@nfs01 scripts]# echo ${name[@]}
jiang yang
[root@nfs01 scripts]# name[1]=bo
[root@nfs01 scripts]# echo ${name[@]}
jiang bo yang
jiang(){
echo nihao
}
jiang 表示调用上面定义的函数
[root@nfs01 scripts]# sh test.sh
nihao
[root@nfs01 scripts]# source test.sh
nihao
[root@nfs01 scripts]# jiang
nihao
jiang(){
echo nihao $1
}
daya(){
echo buhao $1
}
jiang $1
daya $1
[root@nfs01 scripts]# sh test.sh 1
nihao 1
buhao 1
[root@nfs01 scripts]# basename /server/scripts/test.sh
test.sh
[root@nfs01 scripts]# basename /server/scripts/test.sh .sh
test
jiang(){
echo nihao $1
}
daya(){
echo buhao $1
}
jiang
exit 在可能有问题地方加上exit,不在继续向下执行脚本,缩小排查范围
daya
[root@nfs01 scripts]# sh -x test.sh
+ jiang
+ echo nihao
nihao
+ daya
+ echo buhao
buhao
[root@nfs01 scripts]# sh test.sh
nihao
+ daya
+ echo buhao
buhao
+ set +x
标签:shell
原文地址:http://blog.51cto.com/13520772/2092431