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

本文提供了多个Shell脚本实例,包括列出系统上的所有用户、在指定目录中搜索特定字符串、显示目录内所有符号链接文件等。通过这些示例,读者可以了解如何利用Shell脚本来高效地完成日常任务。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值