博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1.5. Loops for, while and until
阅读量:6168 次
发布时间:2019-06-21

本文共 2354 字,大约阅读时间需要 7 分钟。

1.5.1. for

#!/bin/bashfor i in 1 2 3 4 5do   echo "Welcome $i times"donefor i in $( ls ); do    echo item: $idonefor i in `seq 1 10`;do    echo $idonefor i in {1..5}do   echo "Welcome $i times"donefor (( c=1; c<=5; c++ ))do	echo "Welcome $c times..."donefor ((i=1; $i<=9;i++)); do echo $i; done
for i in {0..10..2}do    echo "Welcome $i times"donefor i in $(seq 1 2 20)do   echo "Welcome $i times"done

单行实例

for ip in {1..10};do echo $ip; donefor i in `seq 1 10`;do echo $i;donefor ip in {81..92}; do ssh root@172.16.3.$ip date; donefor n in  {23..32} {49,50} {81..92}; do mkdir /tmp/$n; echo $n; done
for keyword in bash cmd lsdo	echo $keyworddone string="aaa bbb ccc ddd" && for word in $string; do echo "$word"; done	files=( "/etc/passwd" "/etc/group" "/etc/hosts" )for file in "${files[@]}"do    echo $filedone

infinite loops

#!/bin/bashfor (( ; ; ))do   echo "infinite loops [ hit CTRL+C to stop]"done

find file

#!/bin/bashfor file in /etc/*do	if [ "${file}" == "/etc/resolv.conf" ]	then		countNameservers=$(grep -c nameserver /etc/resolv.conf)		echo "Total  ${countNameservers} nameservers defined in ${file}"		break	fidone

backup file

#!/bin/bashFILES="$@"for f in $FILESdo        # if .bak backup file exists, read next file	if [ -f ${f}.bak ]	then		echo "Skiping $f file..."		continue  # read next file and skip cp command	fi        # we are hear means no backup file exists, just use cp command to copy file	/bin/cp $f $f.bakdone
for n in  {23..32} {49,50} {81..92}; do mkdir /tmp/$n; echo $n; done

1.5.2. while

#!/bin/bashCOUNTER=0while [  $COUNTER -lt 10 ]; do    echo The counter is $COUNTER    let COUNTER=COUNTER+1done
while read name agedo	echo $name $agedone << EOFneo 30jam 31john 29EOFwhile read name agedo	[[ $age -gt 30 ]] && echo $namedone << EOFneo 30jam 31john 29EOF
$ cat mount.sh#!/bin/shwhile read LINEdo	s=`echo $LINE|awk '{print $1}'`	d=`echo $LINE|awk '{print $2}'`	umount -f $d	mount -t nfs4 $s $ddone < mount.conf$ cat mount.conf172.16.0.1:/	/www/logs/1172.16.0.2:/	/www/logs/2172.16.0.3:/	/www/logs/3172.16.0.4:/	/www/logs/4172.16.0.5:/	/www/logs/5

读一行

while IFS='' read -r line || [[ -n "$line" ]]; do	echo "Text read from file: $line"done < "$1"

1.5.3. until

#!/bin/bashCOUNTER=20until [  $COUNTER -lt 10 ]; do    echo COUNTER $COUNTER    let COUNTER-=1done

原文出处:Netkiller 系列 手札

本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

你可能感兴趣的文章
Shell实战之函数的高级用法
查看>>
NASA制做模拟系外行星环境 发现了热木星大气不透明的原因
查看>>
Slog67_后端框架Skynet之Makefile解读
查看>>
iOS ShareSDK桥接技术
查看>>
BAT面试须知:Java开发的招聘标准
查看>>
WeUI for 小程序–使用教程
查看>>
[vuex] unknown action type
查看>>
深入浅出 Java 并发编程 (1)
查看>>
【神器】可视化创建骨架屏
查看>>
数组左边减去右边数值的最大差值
查看>>
SVN用法
查看>>
js中的promise和then
查看>>
队列组 iOS之多线程GCD(二)
查看>>
Flutter滚动, 中间显示整图, 前后露出部分图
查看>>
Flutter入坑指南:开发环境搭建
查看>>
跨Navigation跳转(类似微信)方案二
查看>>
JavaScript 复习之 对象的继承
查看>>
从开源小白到 Apache Member,我的成长之路
查看>>
logstash简介
查看>>
Java多线程之synchronized理论
查看>>