bash里的for循环
Bash For Loop
简单例子
1 | for i in 1 2 3 4 5; do echo "counter: $i"; done |
脚本
1 |
|
变量
1 | for file in *; do echo "$file"; done |
1 | seq 25 30 |
1 | for counter in $(seq 1 255); do echo "$counter"; done |
1 | for counter in $(seq 1 255); do ping -c 1 "10.0.0.$counter"; done |
range
1 | for counter in {1..255}; do ping -c 1 10.0.0.$counter; done |
1 | for counter in {1..255..5}; do echo "ping -c 1 10.0.0.$counter"; done |
chain
1 |
|
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 |
例子
- 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 |
|
- Rename all *.txt files to remove the file extension
1 | 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 |
|
- 批量转换图片格式
1 | for i in *.jpg; do convert $i ${i%.jpg}.png; done |