您的位置:首页 > 运维架构 > Shell

shell实例(十一) ----循环,select结构

2011-03-09 23:58 357 查看
1.列出系统上所有用户

#! /bin/sh
PASSWORD_FILE=/etc/passwd
n=1
for name in $(awk 'BEGIN{FS=":"} {print $1}' < "$PASSWORD_FILE" )
do
echo "USER #$n = $name"
let "n += 1"
done

exit 0

2.在目录的所有文件中查找源字串

#! /bin/sh
directory=/usr/bin/
fstring="Free Software Foundation"
for file in $( find $directory -type f -name '*' | sort )
do
strings -f $file | grep "Sfstring" | sed -e "s%$directory%%"
done

exit 0

3.列出目录中所有有符号链接的文件

#! /bin/sh
directory=${l- `pwd`}
ARGS=1
if [ $# -ne "$ARGS" ]
then
directory=`pwd`
else
directory=$1
fi

echo "symbolic links in directory /"$directory/""
for file in "$( find $directory -type l )"
do
echo "$file"
done | sort

exit 0

4.多条件的while循环(以最后一个条件作为判断是否退出)

#! /bin/sh
var1=unset
previous=$var1
while echo "previous-variable = $previous"
echo
previous=$var1
[ "$var1" != "end" ]
do
echo "Input variable #1 (end to exit)"
read var1
echo "variable #1 = $var1"
done

exit 0

5.until循环

#! /bin/sh
END_CONDITION=end
until [ "$var1" = "$END_CONDITION" ]
do
echo "Input variable #1 "
echo "($END_CONDITION to exit)"
read var1
echo "variable #1 = $var1"
echo
done
exit 0

6.使用select来创建菜单

#! /bin/sh
PS3='Choose your favorite vegetable: '
echo

select vegetable in "beans" "carrots" "potatoes" "onions" "rutabagas"
do
echo
echo "Your favorite veggie is $vegetable."
echo "Yuck"
echo
break
done

exit 0

7.使用函数中select结构创建菜单

#! /bin/sh
PS3='Choose your favorite vegetable: '
echo

choice_of(){
select vegetable
do
echo
echo "You favorite veggie is $vegetable."
echo "Yuck!"
echo
break
done
}

choice_of beans rice carrots radishes tomatoes spinach

exit 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: