shell编程三-循环语句
for循环
for var in list
do
commands
done
C语言风格的for循环:
#!/bin/bash
for (( i=1; i <= 10; i ++ ))
do
echo value is $i
done
#!/bin/bash
for (( a=1, b=10; a <= 10; a++,b-- ))
do
echo "$a - $b"
done
while循环
while test command do commands done
#!/bin/bash
var=10
while [ $var -gt 0 ]
do
echo $var' > 0'
var=$[ $var - 1 ]
done
until 循环
#!/bin/bash
var=10
until [ $var -lt 0 ]
do
echo $var' > 0'
var=$[ $var - 1 ]
done
循环其他功能
循环控制
跟其他语言一样,控制循环:
- break
- continue
循环输出
#!/bin/bash
for file in /root/*
do
if [ -d $file ]
then
echo ${file}是目录
fi
done > output.txt
示例
读取文件变量,,
区分:
#!/bin/bash
input="users.csv"
while IFS=',' read -r userid name
do
echo "adding $userid"
useradd -c "$name" -m $userid
done < "$input”