shell脚本第五部分--for循环
![](https://i-blog.csdnimg.cn/blog_migrate/8f6aebd551af58062703373323806d6d.jpeg)
使用循环从1加到100
第一种:使用while..do执行
vi sh13.sh
#!/bin/bash
#Program: use while to 1 to 100
#History:2020-04-12 jack v1.0.0
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
i=0
s=0
while [ "$i" -lt 100 ]
do
i=$(($i+1))
s=$(($s+$i))
done
echo "1+2+...+$i=$s"
sh sh14.sh
第二种:使用until..do执行
vi sh13-2.sh
#!/bin/bash
i=0
s=0
until [ "$i" = 100 ]
do
i=$(($i+1))
s=$(($s+$i))
done
echo "1+2+...+$i=$s"
sh sh13-2.sh
第三种:使用for循环执行
vi sh14.sh
#!/bin/bash
#Program: use for to add 1 to 100
#History: 2020-04-12 jack v1.0
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
s=0
for((i=0;i<=100;i++))
do
s=$(($s+$i))
done
echo "1+2+...+100=$s"
sh sh14.sh
使用for输出动物名字
vi sh15.sh
#!/bin/bash
#Program:use for to display some information
#History: 2020-04-12 jack v1.0.1
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
for animal in cat dog pig
do
case $animal in
"cat")
echo "$animal miao miao"
;;
"dog")
echo "$animal wang wang"
;;
"pig")
echo "$animal buhuijiao"
;;
esac
done
sh sh15.sh
使用for输出一个目录下文件的属性
vi sh16.sh
#!/bin/bash
#Program: use for to display a directory's filetype and permission
#History:2020-04-12 jack v1.0.1
PATH=/bin:/sbin:/usr/bin:usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
read -p "Please input a directory: " dir
if [ -z "$dir" -a ! -d "$dir" ]; then
echo "you have input nothing or $dir is NOT a directory!"
exit 0
fi
file=`ls $dir`
for filename in $file
do
test -f "$dir/$filename" && filetype="is a regular file"
test -d "$dir/$filename" && filetype="is a directory"
test -p "$dir/$filename" && filetype="is a PIPE file"
test -b "$dir/$filename" && filetype="is a block device"
test -c "$dir/$filename" && filetype="is a character device"
test -S "$dir/$filename" && filetype="is a socket file"
test -L "$dir/$filename" && filetype="is a link file"
test -r "$dir/$filename" && per="$per readable"
test -w "$dir/$filename" && per="$per writable"
test -x "$dir/$filename" && per="$per executable"
test -u "$dir/$filename" && per="$per set UID"
test -g "$dir/$filename" && per="$per set GID"
test -k "$dir/$filename" && per="$per sticky bit"
echo "the file $dir/$filename you have input $filetype,and the permission is $per"
filetype=""
per=""
done
sh -n sh16.sh 检查脚本有无语法错误
sh sh16.sh 执行
注:脚本中if语句中的-x 表示如果文件存在且可执行则为真,-z表示字符串长度为0则为真,-a 表示如果文件存在则为真 -d表示如果文件存在且是一个目录则为真