shell脚本中for循环及while循环写法

2022/2/11 7:15:20

本文主要是介绍shell脚本中for循环及while循环写法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

for循环

例1

**展示上面的数组

#!/bin/bash
#脚本名称为222.sh
name1="nihao1"
name2="nihao2"
name3="nihao3"
name4="nihao4"
for i in {1..4}
do
    #使用a作为中间变量,再使用间接引用a的值
    a=name$i
    echo ${a}
    echo ${!a}
done

执行上面的脚本显示如下,看到结果猜想下上面用法的意义:
在这里插入图片描述
展示a~z

for i in {a..z}
do 
	echo $i;
done

例2

seq 默认步长为1

for i in \`seq 0 4\`
do
	echo $i;
done、

seq 设置步长为2

for i in \`seq 0 2 10\`
do
	echo $i;
done

例3

#!/bin/sh
for (( i=0; i<=5; i++))
do
	echo "my number is" $i;
done

例4 批量创建用户、删除用户

批量创建用户、询问是否需要删除用户,回答[Y/y]表示需要删除,回答其他不删除用户仅展示用户名

#!/bin/sh
set +x;
i=1;
j=3;
#循环创建用户
for (( i; i<=j; i++))
do
	useradd xingxing$i;
	echo "xingxing123" |passwd --stdin xingxing$i;
done

echo "3个用户已经创建成功,密码为"xingxing123""


read  -p  "是否要删除用户?输入[Y/y]表示删除用户,输入其他表示不删除用户" YORN
x=1;
y=3; #也可以直接用上面的变量
if [ $YORN = "Y" -o $YORN = "y" ];
then
	echo "将被删除的用户名称为:xingxing$x;"
	for (( x; x<=y; x++))
	do
		userdel xingxing$x;
		rm -rf /home/xingxing$x;
	done
else	
	echo "新建的用户有:"
	for ii in \`seq 1 $y\`
	do
		echo "xingxing$ii"
	done
fi
for line in `cat filename(待读取的文件)`
do
    echo $line
done

while 循环

例1 从命令行读取参数

错误(<<中间应该有个空格)没有空格执行失败

while read line;do echo $line;**done <<(find /dev -type f -print)

下面两种用户都可以正确执行

while read line;do echo $line;done < <(find /dev -type f -print)
while read line;do echo $line;done <<<"`find /dev -type f -print`"

例2 从文件读取参数

#!/bin/bash
while read line
do
	echo $line
done <1111.txt
cat filename | while read line
do
    echo $line
done

读取脚本后面的参数

在循环中用shift 命令可以顺序地将脚本后面的参数顺序读取,如下面的脚本

#!/bin/bash
#文件名为shift.sh
while [ $# -ne 0 ]
do
echo $1
shift
done

执行结果如下:
在这里插入图片描述

读取变量的值

#!/bin/bash
#文件名为shift.sh
i=0
sum=0
while ((i<=10));
do
let sum+=i
echo $sum
let ++i
done


这篇关于shell脚本中for循环及while循环写法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程