基于linux下的shell常用语句(二)

if语句:

if
then
elif
then
else
fi
一、shell脚本:执行此脚本检测输入的是什么类型(普通文件、目录、链接、块设备、字符设备...)
#!/bin/bash
Check_file()
{
      if
        ["$1"  "$2"]
        echo "$2" is $3
        exit  0
        fi
}
if
["$#" -ne "1" ]
then
          echo "please  input a file follow  script!!!"
elif
[!  -e "$1"]
then
          echo  "$1  is not exist!!"
else
        Check_file  -L $1 link
        Check_file  -f $1 "common  file"
        Check_file  -S $1 socket
        Check_file  -b $1 block
        Check_file  -c $1 character
        Check_file  -d $1 directory

fi


二、shell脚本:

检测用户文件、密码文件

(1)文件数量不对报错

(2)文件不存在报错

(3)文件行数差异报错

(4)当文件内用户存在时,显示存在,不改变其密码,当用户不存在时建立用户,并设定相应密码

 #!/bin/bash
if
[ "$#" -ne  "2" ]
then
          echo please input file  follow script!!
          exit 1
elif
[ !  -e  "$1" ]
then           
           echo "$1"  is not exist"
           exit 1
elif
[ !  -e  "$2" ]
then
           echo "$2"  is not exist"
           exit 1
elif
USERFILE_LINE=`awk 'BEGIN{N=0}{n++}END{print N}' $1`
PASSFILE_LINE=`awk 'BEGIN{N=0}{n++}END{print N}' $2`
["$USERFILE_LINE"  -ne  "$PASSFILE_LINE"]
then           
              echo   "$1's line number  is different from  $2's line number"
           exit 1
fi
for
 LINE_NUM in `seq 1 $USERFILE_LINE`
do USERNAME=`sed -n "${LINE_NUM}p" $1`
   PASSWORD=`sed -n "${LINE_NUM}p" $2`
   useradd $USERNAME &&{
    echo  $PASSWORD| passwd --stdin  $USERNAME &>/dev/null && echo $USERNAME created!!
}

done


三、shell脚本:

当输入为dog时显示cat,当输入为cat时显示dog,当不为这两个时显示错误

#!/bin/bash
if
[ "$1"="dog" ]
then
    echo  cat
elif
[ "$1"="cat"]
then
     echo  dog
else
       echo  error:please input cat or dog follow script

fi



case语句:

case  $1 in
         )
      echo
       ;;
         )
      echo
       ;;
       *)
       echo 
esac

四、shell脚本:

当输入为dog时显示cat,当输入为cat时显示dog,当不为这两个时显示错误

#!/bin/bash
case $1 in
       dog)
       echo   cat
        ;;
       cat)
       echo    dog
        ;;
       *)
        echo error

esac


expect语句:

yum install expect

五、shell脚本:

自动链接访问别人的机子

[root@localhost mnt]# vim auto_connect.exp
#!/usr/bin/expect
set timeout 5
set IP [ lindex  $argv 0 ]
set PASS [ lindex $argv 1 ]
spawn ssh root@$IP
expect {
        "yes/no" { send "yes\r";exp_continue }
        "password" { send "$PASS\r }
}
interact

猜你喜欢

转载自blog.csdn.net/xdmaidou/article/details/80837092