read,for,case,while,if简单例子

Read多用于从某文件中取出每行进行处理

$ cat read.sh
#!/bin/bash

echo "using read"
cat name.txt |
while read name
do
echo "name is $name"
done

For多用于从一堆文件中取出某个文件进行处理

$ cat for.sh
#!/bin/bash

echo "using for"
i=0
for file in *.txt
do
echo "file name is $file"
i=`expr $i + 1`
done
echo "we have $i files"

Case多用于给Shell脚本的后面跟取不同参数进行处理

$ cat case.sh
#!/bin/bash

echo "using case"

case $1 in
-a)
echo "you are using -a"
;;

-b)
echo "you are using -b"
;;

*)
echo "you input is not correct, and please input -a or -b"
;;
esac

If多用于各种条件判断,例如比大小,文件是否存在等

$ cat if.sh
#!/bin/bash

echo "using if"
if [ -f $1 ]
then
echo "$1 is a regular file"
elif [ -d $1 ]
then
echo "$1 is a directory"
fi

注:$1代表脚本后面跟着的一个参数

原文地址:https://www.cnblogs.com/oskb/p/4724531.html