bash里的for循环

Bash For Loop

简单例子

1
for i in 1 2 3 4 5; do echo "counter: $i"; done

脚本

1
2
3
4
5
#!/bin/bash
for i in 1 2 3 4 5
do
echo "counter: $i"
done

变量

1
2
3
4
for file in *; do echo "$file"; done
file1.txt
file2.txt
file3.txt
1
2
3
4
5
6
7
seq 25 30
25
26
27
28
29
30
1
for counter in $(seq 1 255); do echo "$counter"; done
1
2
3
4
for counter in $(seq 1 255); do ping -c 1 "10.0.0.$counter"; done
PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.
PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.
...

range

1
for counter in {1..255}; do ping -c 1 10.0.0.$counter; done
1
2
3
4
5
for counter in {1..255..5}; do echo "ping -c 1 10.0.0.$counter"; done
ping -c 1 10.0.0.1
ping -c 1 10.0.0.6
ping -c 1 10.0.0.11
ping -c 1 10.0.0.16

chain

1
2
3
4
5
6
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Hold on, connecting to 10.0.1.$i"
ssh root@"10.0.1.$i" uptime
echo "All done, on to the next host!"
done
1
for i in 1 2 3 4 5; do echo "Hold on, connecting to 10.0.1.$i"; ssh root@"10.0.1.$i" uptime; echo "All done, on to the next host"; done

例子

  1. For each user on the system, write their password hash to a file named after them
1
for username in $(awk -F: '{print $1}' /etc/passwd); do grep $username /etc/shadow | awk -F: '{print $2}' > $username.txt; done
1
2
3
4
5
#!/bin/bash
for username in $(awk -F: '{print $1}' /etc/passwd)
do
grep $username /etc/shadow | awk -F: '{print $2}' > $username.txt
done
  1. Rename all *.txt files to remove the file extension
1
for filename in *.txt; do mv "$filename" "${filename%.txt}"; done
1
2
3
4
5
#!/bin/bash
for filename in *.txt
do
mv "$filename" "${filename%.txt}"
done
  1. Use each line in a file as an IP to connect to
1
for ip in $(cat ips.txt); do ssh root@"$ip" yum -y update; done
1
2
3
4
5
#!/bin/bash
for ip in $(cat ips.txt)
do
ssh root@"$ip" yum -y update
done
  1. 批量转换图片格式
1
for i in *.jpg; do convert $i ${i%.jpg}.png; done