脚本练习-2

脚本01.sh:

给定一个文件:

如果是一个普通文件,就显示之;

如果是一个目录,亦显示之;

否则,此为无法识别之文件;

#!/bin/bash
#
read -p "Enter your file: " FILE
if [ ! -e $FILE ];then
    echo "no such file."
else
    if [ -f $FILE ];then
        echo "common file."
    elif [ -d $FILE ];then
        echo "directory."
    else
        echo "unknow file."
    fi
 fi


脚本02.sh:

能接受一个参数(文件路径)

判定:此参数如果是一个存在的文件,就显示“OK.”;否则就显示"No such file."

#!/bin/bash
#
read -p "Enter your file name :" NAME
if [ -e $FILE ];then
    echo "OK."
else
    echo "no such file."
fi


脚本03.sh:

给脚本传递两个参数(整数);

显示此两者之和,之乘积;

#!/bin/bash
#
if [ $# != 2 ];then
    echo "unknow commend"
else
    echo "SUM=$[$1+$2]"
    echo "SUM=$[$1*$2]"
fi


脚本04.sh:

写一个脚本完成一下任务:

1、使用一个变量保存一个用户名;

2、删除此变量中的用户,且一并删除其主目录;

3、显示“用户删除完成”类的信息;

#!/bin/bash
#
read -p "Enter your username :" NAME
id $NAME &>/dev/null
if [ $? == 0 ];then
    userdel -r $NAME &> /dev/null
    echo "delete user success."
else
    echo "no such user"
fi


脚本05.sh:

传递一个参数(单字符就行)给脚本,如参数为q、Q、quit或Quit,就退出脚本;否则,就显示用户的参数;

#!/bin/bash
#
read -p "Please input your choice 
q|Q for quit
any to continue
:"  CHOICE
if [ $CHOICE == 'q' ];then
    exit 0
elif [ $CHOICE == 'Q' ];then
    exit 0
else
    echo "This is your input: $CHOICI"
fi


脚本06.sh:

传递三个参数给脚本,第一个为整数,第二个为算术运算符,第三个为整数,将计算结果显示出来,要求保留两位精度。

#!/bin/bash
#
if [[ $1 =~ ^[0-9]+$ && $2 =~ ^[+,-,*,/]+$ && $3 =~ ^[0-9]+$ ]];then
    echo "scale=2;$1$2$3" | bc
else
    echo "Unknow."
fi

    笔记:变量的匹配做if的条件需要用双“[]”,“=~”是匹配的意思,“+”前边的字符出现至少一次。

脚本07.sh:

传递3个参数给脚本,参数均为用户名。将此些用户的帐号信息提取出来后放置于/tmp/testusers.txt文件中,并要求每一行行首有行号。

#!/bin/bash
#
if [ $# != 3 ];then
    echo "please enter three usernames!"
else
    rm -f ./testuser.txt &> /dev/null
    grep ^$1 /etc/passwd &> /dev/null && echo "1 `grep ^$1 /etc/passwd`" >> ./testuser.txt || echo "1 there is no user $1" >> ./testuser.txt
    grep ^$2 /etc/passwd &> /dev/null &&  echo "2 `grep $2 /etc/passwd`" >> ./testuser.txt || echo "2 there is no user $2" >> ./testuser.txt
    grep ^$3 /etc/passwd &> /dev/null &&  echo "3 `grep $3 /etc/passwd`" >> ./testuser.txt || echo "3 there is no user $3" >> ./testuser.txt
fi


脚本08.sh:

判断当前主机的CPU生产商,其信息在/proc/cpuinfo文件中vendor id一行中。

如果其生产商为AuthenticAMD,就显示其为AMD公司;

如果其生产商为GenuineIntel,就显示其为Intel公司;

否则,就说其为非主流公司;

#!/bin/bash
#
STRING=`greo ^vendor /proc/cpuinfo | cut -d ":" -f 2`
if [ $STRING == GenuineIntel ];then
    echo "Intel."
elif [ $STRING == AuthenticAMD ];then
    echo "AMD."
else 
    echo "others"
fi


脚本09.sh:

给脚本传递三个整数,判断其中的最大数和最小数,并显示出来。

#!/bin/bash
#
if [ $# != 3 ];then
    echo "please enter three number."
else
    if [ $1 -gt $2 ];then
        MAX=$1
        MIN=$2
    else
        MAX=$2
        MIN=$1
    fi
    
    if [ $MAX -lt $3 ];then
        MAX=$3
    fi
    
    if [ $MIN -gt $3 ];then
        MIN=$3
    fi
    echo MAX=$MAX
    echo MIN=$MIN
fi


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章