shell实例(四)

    技术2022-05-19  20

    1.定时输入

    一、

    #! /bin/shTIMEOUT=3TIMELIMIT=3printAnswer(){  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 "timerOnread answerprintAnswerexit 0

     

    二、

    #! /bin/shINTERVAL=5timeout_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/shTIMELIMIT=4read -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 -nuroot[root@localhost yjg]# iduid=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/shROOT_UID=0if [ "$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=rootusername=`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/shE_BADARGS=65if [ ! -n "$1" ]then  echo "Uage: `basename $0` argument1 argument2 etc."  exit "$E_BADARGS"fi

    echo

    index=1echo "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=1echo "Listing args with /"/$@/":"for arg in "$@"do  echo "Arg #$index = $arg"  let "index+=1"doneecho "Arg list seen as separate words."

    echo

    index=1echo "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


    最新回复(0)