shell脚本基础知识梳理<四>:流程控制for-成都快上网建站

shell脚本基础知识梳理<四>:流程控制for

for语句的使用格式
for var in n1,n2,nn
do
指令1
指令2
...
done

创新互联是一家朝气蓬勃的网站建设公司。公司专注于为企业提供信息化建设解决方案。从事网站开发,网站制作,网站设计,网站模板,微信公众号开发,软件开发,微信平台小程序开发,10余年建站对成都iso认证等多个方面,拥有丰富的营销推广经验。

for var in item1 item2 ... itemN; do command1; command2… done;

实例1
#!/bin/bash
#使用字面字符串
for x in centos ubuntu gentoo opnesuse
do
echo "$x";
done

#若列表中包含空格字符必须使用引号包含起来
for x in Linux "Gnu Hurd" FreeBSD "Mac OS X"
do
echo "$x";
done
#eval 变量引用
for x in ls "df -h" "du -sh"
do
echo "===$x==" ; eval $x
done

运行结果
[root@localhost shell]# sh for1.sh
centos
ubuntu
gentoo
opnesuse
Linux
Gnu Hurd
FreeBSD
Mac OS X
===ls==
case2.sh case4.sh for1.sh if-elif.sh liu myshell1.sh
case3.sh case.sh if-elif-if-else.sh if-if.sh liub qq
===df -h==
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/centos-root 27G 5.9G 22G 22% /
devtmpfs 475M 0 475M 0% /dev
tmpfs 487M 0 487M 0% /dev/shm
tmpfs 487M 7.7M 479M 2% /run
tmpfs 487M 0 487M 0% /sys/fs/cgroup
/dev/sda1 1014M 133M 882M 14% /boot
tmpfs 98M 0 98M 0% /run/user/0
===du -sh==
36K .
[root@localhost shell]#

实例2

!/bin/bash
#使用变量
i=1
weekdays="Mon Tue Wed Thu Fri"
for day in $weekdays ; do
echo "Weekday $((i++)) : $day"
done

#默认是空格若不设定输出的结果是

#Linux
#'Gnu
#Hur'
#FeeBSD
#'Mac
#OS
#X'
#Others

#设定IFS

IFS=:
OSlist="Linux:'Gnu Hur':FeeBSD:'Mac OS X'"
for x in $OSlist Others; do
echo "$x"
done

运行结果
[root@localhost shell]# sh for2.sh
Weekday 1 : Mon
Weekday 2 : Tue
Weekday 3 : Wed
Weekday 4 : Thu
Weekday 5 : Fri
Linux
'Gnu Hur'
FeeBSD
'Mac OS X'
Others
[root@localhost shell]#

实例3

#!/bin/bash
#使用位置变量$@, in $@可以省略

i=1
for day;do
echo -n "位置参数 $((i++)): $day "
case $day in
[Mm]on|[Tt]ue|[Ww]ed|[Tt]hu|[Ff]ri)
echo " (weekday)"
;;
[Ss]at|[Ss]un)
echo " (weekeno)"
;;
*)
echo " (Invalid weekday)"
;;
esac
done

输出结果

[root@zabbix shell]# sh for3.sh mon tue wed thu fri sat sun
位置参数 1: mon (weekday)
位置参数 2: tue (weekday)
位置参数 3: wed (weekday)
位置参数 4: thu (weekday)
位置参数 5: fri (weekday)
位置参数 6: sat (weekeno)
位置参数 7: sun (weekeno)

实例4

#!/bin/bash
#使用文件名或目录
for frname in *
do
#使用命令替换成小写文件名并赋予给变量fn;
fn=$(echo $frname | tr A-Z a-z)
#判断新生产的文件名是否与原名相同,若不同改成小写
if [[ $frname != $fn ]];then mv $frname $fn;fi
#[[ $frname != $fn ]]&& mv $frname $fn
#[[ $frname == $fn ]] || mv $frname $fn
done

运行结果

[root@zabbix shell]# touch ABC
[root@zabbix shell]# mkdir qwe
[root@zabbix shell]# sh for4.sh
[root@zabbix shell]# ll
总用量 8
-rw-r--r-- 1 root root 0 8月 26 15:23 abc
-rw-r--r-- 1 root root 330 8月 26 15:11 for3.sh
-rw-r--r-- 1 root root 218 8月 26 15:23 for4.sh
drwxr-xr-x 2 root root 6 8月 26 15:23 qwe

实例5

#!/bin/bash
for i in *.zip
do
#去掉尾部是.zip部分
j="${i%.zip}";mkdir "$j" && unzip -d "$j" "$i"
echo $j
#j="${i%.zip}"
#echo $j
done

执行结果

[root@zabbix shell]# sh for5.sh
Archive: adf.zip
extracting: adf/abc
inflating: adf/for3.sh
inflating: adf/for4.sh
extracting: adf/qq.zip
creating: adf/qwe/
extracting: adf/we.zip
adf
Archive: qq.zip
extracting: qq/abc
inflating: qq/for3.sh
inflating: qq/for4.sh
creating: qq/qwe/
extracting: qq/we.zip
qq
Archive: we.zip
extracting: we/abc
inflating: we/for3.sh
inflating: we/for4.sh
creating: we/qwe/
we

实例 6

!/bin/bash
#用命令的执行结果作为列表
i=1
for usrname in awk -F: '{print $1}' /etc/passwd
do
echo "Username $((i++)) : $usrname"
done
echo "***"
for line in $(cat /etc/yum.conf|egrep -v "^/|^#")
do
echo "$line"
done

echo "seq 生成序列"
for suffix in $(seq 5)
do
echo "192.168.1.${suffix}"
done

echo "***"
for f in $(ls /var/);do
echo $f
done

执行结果

Username 10 : operator
Username 11 : games
Username 12 : ftp
Username 13 : nobody
Username 14 : systemd-network
Username 15 : dbus
Username 16 : polkitd
Username 17 : sshd
Username 18 : postfix
Username 19 : chrony
Username 20 : www
Username 21 : MySQL
Username 22 : saslauth
Username 23 : zabbix
Username 24 : grafana
Username 25 : ntp


[main]
cachedir=/var/cache/yum/$basearch/$releasever
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
installonly_limit=5
bugtracker_url=http://bugs.centos.org/set_project.php?project_id=23&ref=http://bugs.centos.org/bug_repo
rt_page.php?category=yum
distroverpkg=centos-release


192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5


adm
cache
crash
db
empty
games
gopher

实例7

#!/bin/bash
#判断host
for host in cat /etc/hosts
do
if ping -c1 -w2 $host &>/dev/null
then
echo "Host (${host}) is active."
else
echo "Host (${host}) is down."
fi
done

执行结果

root@zabbix shell]# sh for7.sh
Host (127.0.0.1) is active.
Host (localhost) is active.

实例8

#!/bin/bash
#使用数值
myip="192.168.0"
for num in {1..5}
do
echo "IPAddr $num: $myip.$num"
done

#步长
for num in {1..10..2}
do
echo "Number: $num"
done

执行结果

[root@zabbix shell]# sh for8.sh
IPAddr 1: 192.168.0.1
IPAddr 2: 192.168.0.2
IPAddr 3: 192.168.0.3
IPAddr 4: 192.168.0.4
IPAddr 5: 192.168.0.5
Number: 1
Number: 3
Number: 5
Number: 7
Number: 9

实例 9

#!/bin/bash
for x in {1..5}
do
useradd user${x}
#stdin是接收echo后面的字符串作为密码。stdin是非交换直接传入密码
#passwd 默认是要用终端作为标准输入。加上--stdin可以用任意的做标准输入
echo "centos"|passwd --stdin user${x}
#使用户第一登陆修改密码;chage密码失效命令 -d 上次更改的时间
chage -d 0 user${x}
done

执行结果

[root@localhost shell]# sh for3.sh
Changing password for user user1.
passwd: all authentication tokens updated successfully.
Changing password for user user2.
passwd: all authentication tokens updated successfully.
Changing password for user user3.
passwd: all authentication tokens updated successfully.
Changing password for user user4.
passwd: all authentication tokens updated successfully.
Changing password for user user5.
passwd: all authentication tokens updated successfully.
[root@localhost shell]# ls /home/
user1 user2 user3 user4 user5

重新开个终端用新的用户等如: user1
WARNING: Your password has expired.
You must change your password now and login again!
Changing password for user user1.
Changing password for user1.
(current) UNIX password:

实例 10

!/bin/bash
#for嵌套
for i in 0 1;do
for suffix in {1..5}
do
ip=192.168.$i.${suffix}
if ping -c1 -w2 $ip &>/dev/null
then
echo "$ip is active."
else
echo "Host ($ip) is down."
fi
done
done

执行结果

[root@localhost shell]# sh for4.sh
Host (192.168.0.1) is down.
Host (192.168.0.2) is down.
Host (192.168.0.3) is down.
Host (192.168.0.4) is down.
Host (192.168.0.5) is down.
Host (192.168.1.1) is down.
Host (192.168.1.2) is down.
Host (192.168.1.3) is down.
Host (192.168.1.4) is down.
Host (192.168.1.5) is down.

实例 11

#!/bin/bash
#C语言方式
for ((i=0;i<10;i++))
do
echo $i;
done

for (( i=1; i <= 10; i++ ))
do
echo "$i: $RANDOM"
done

for ((i=1,j=10; i <=5 ; i++, j=j+5))
do
echo "number $i: $j"
done

执行结果

[root@localhost shell]# sh for-c.sh
0
1
2
3
4
5
6
7
8
9
1: 15561
2: 14731
3: 31575
4: 15783
5: 17317
6: 3162
7: 5176
8: 4272
9: 5116
10: 2811
number 1: 10
number 2: 15
number 3: 20
number 4: 25
number 5: 30

实例 12

#!/bin/bash
#
#C语言格式for
s=0
for ((i=1;i<=100;i++))
do
let s=$s+$i
done
echo sum(1..100)=$s

for ((s=0,i=1;i<=100;i++))
do
((s+=i))
done
echo sum(1..100)=$s

for ((s=0,i=1;i<=100;s+=i,i++))
do
:
done
echo sum(1..100)=$s

执行结果

[root@localhost shell]# sh for-c2.sh
sum(1..100)=5050
sum(1..100)=5050
sum(1..100)=5050


本文名称:shell脚本基础知识梳理<四>:流程控制for
浏览路径:http://kswjz.com/article/pjipcp.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流