for循环:(每读取一行在字符串下面添加#号)
[root@localhost ]# cat /etc/passwd|awk -F ':' '{print $3}'|tail -5 > test1.txt
[root@localhost ]# cat test1.txt
989
72
70
38
1000
[root@localhost ]# cat test.sh
#!/bin/bash
for xty in `cat test1.txt`;do ##或者$() 或者直接定义字符
echo $xty
echo "##############"
done
[root@localhost ]# sh test.sh
989
##############
72
##############
70
##############
38
##############
1000
##############
while循环:
while循环:要有退出条件,否则就成为死循环
用法一:循环文件每一行数据
[root@localhost ]# cat /etc/passwd|tail -5 > test1.txt
[root@localhost ]# ls
test1.txt test.sh
[root@localhost ]# cat test1.txt
gnome-initial-setup:x:989:983::/run/gnome-initial-setup/:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
roo:x:1000:1000:root:/home/roo:/bin/bash
[root@localhost ]# cat test.sh
#!/bin/bash
file=test1.txt
while read F; do
echo "$F" | tr [a-z] [A-Z] >> test2.txt ##每读取一行转换为大写字符追加到test2.txt
done < $file
[root@localhost ]# sh -x test.sh
+ file=/root/test/test1.txt
+ read F
+ echo gnome-initial-setup:x:989:983::/run/gnome-initial-setup/:/sbin/nologin
+ tr '[a-z]' '[A-Z]'
+ read F
+ echo tcpdump:x:72:72::/:/sbin/nologin
+ tr '[a-z]' '[A-Z]'
+ read F
+ echo 'avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin'
+ tr '[a-z]' '[A-Z]'
+ read F
+ echo ntp:x:38:38::/etc/ntp:/sbin/nologin
+ tr '[a-z]' '[A-Z]'
+ read F
+ tr '[a-z]' '[A-Z]'
+ echo roo:x:1000:1000:root:/home/roo:/bin/bash
+ read F
[root@localhost ]# cat test2.txt
GNOME-INITIAL-SETUP:X:989:983::/RUN/GNOME-INITIAL-SETUP/:/SBIN/NOLOGIN
TCPDUMP:X:72:72::/:/SBIN/NOLOGIN
AVAHI:X:70:70:AVAHI MDNS/DNS-SD STACK:/VAR/RUN/AVAHI-DAEMON:/SBIN/NOLOGIN
NTP:X:38:38::/ETC/NTP:/SBIN/NOLOGIN
ROO:X:1000:1000:ROOT:/HOME/ROO:/BIN/BASH
用法二:计算1-5整数的总和
[root@localhost test]# cat test.sh
#!/bin/bash
declare -i I=1
declare -i sum=0
while [ $I -le 5 ]; do ##使用while循环计算1到5整数的和
let sum+=$I
let I++
done
echo "$sum"
[root@localhost test]# sh -x test.sh
+ declare -i I=1
+ declare -i sum=0
+ '[' 1 -le 5 ']'
+ let sum+=1
+ let I++
+ '[' 2 -le 5 ']'
+ let sum+=2
+ let I++
+ '[' 3 -le 5 ']'
+ let sum+=3
+ let I++
+ '[' 4 -le 5 ']'
+ let sum+=4
+ let I++
+ '[' 5 -le 5 ']'
+ let sum+=5
+ let I++
+ '[' 6 -le 5 ']'
+ echo 15
15
标签:echo,循环,let,Linux,test,格式,txt,root,localhost From: https://www.cnblogs.com/xiongty/p/16851770.html