shell实例(四)

1.定时输入

一、

#! /bin/sh
TIMEOUT=3
TIMELIMIT=3
printAnswer()
{
  if [ "$answer" = TIMEOUT ]
  then
    echo $answer
  else
    echo "Your favorite veggie is $answer"
    kill $!
  fi
}

timerOn()
{
  sleep $TIMELIMIT && kill -s 14 $$ & ----??
}

Int14Vector()
{
  answer="TIMEOUT"
  printAnswer
  exit 14
}

trap int14Vector 14 -----???
echo "What is your favorite vegetable "
timerOn
read answer
printAnswer
exit 0

 

二、

#! /bin/sh
INTERVAL=5
timeout_read() {
  timeout=$1
  varname=$2
  old_tty_settings=`stty -g` ---保存当前stty状态到 old_tty_settings
  stty -icanon min 0 time ${timeout}0 -----禁用规范输入
  eval read $varname --------接受键盘输入s
}

echo; echo -n "What's your name? Quick! "
timeout_read $INTERVAL your_name

echo

if [ ! -z "$your_name" ]
then
 echo "Your name is $your_name."
else
 echo "Timed out."
fi

echo

exit 0

 

三、

#! /bin/sh
TIMELIMIT=4
read -t $TIMELIMIT variable ----------在指定时间内输入信息
echo

if [ -z "$variable" ]
then
 echo "Timed out,variable  still unset."
else
 echo "variable = $variable"
fi

exit 0

 

四、判断是否是root用户

[root@localhost yjg]# id -nu
root
[root@localhost yjg]# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel) context=root:system_r:unconfined_t
[root@localhost yjg]# vi 9-5.sh

#! /bin/sh
ROOT_UID=0
if [ "$UID" -eq "$ROOT_UID" ]
then
  echo "You are root."
else
  echo "You are just an ordinary user (but mom loves you just the same)."
fi

ROOTUSER_NAME=root
username=`id -nu`
if [ "$username" = "$ROOTUSER_NAME" ]
then
  echo "Rooty,toot,toot. You are root."
else
  echo "You are just a regular fella."
fi

exit 0

 

五、通过$*和$@列出所有的参数

#! /bin/sh
E_BADARGS=65
if [ ! -n "$1" ]
then
  echo "Uage: `basename $0` argument1 argument2 etc."
  exit "$E_BADARGS"
fi

echo

index=1
echo "Listing args with /"/$*/":"
for arg in "$*"
do
 echo "Arg #$index = $arg"
 let "index+=1"
done

echo "Enter arg list seen as single word."

echo

index=1
echo "Listing args with /"/$@/":"
for arg in "$@"
do
  echo "Arg #$index = $arg"
  let "index+=1"
done
echo "Arg list seen as separate words."

echo

index=1
echo "Listing args with /$* (unquoted):"
for arg in $*
do
 echo "Arg #$index = $arg"
 let "index+=1"
done

echo "Arg list seen as separate words."
exit 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值