shell 脚本例子

1、shell脚本多路分支语句:
read score                  //读终端的输入数据
if  [ $score -lt 0  -o $score -gt 100 ]             
then
     echo "error"                                                   //如果score小于0或大于100,则执行相应操作
    exit
fi
info=` expr $score / 10`         //变量的赋值,expr算术运算命令
case $info  in
     10 | 9 | 8)
        echo "A"            //info为10或9或8时,打印A
         ;;
    7 | 6) 
        echo "B"
         ;;
     *)
        echo "NO PASS"
         ;;
esac
2、
string="abc d"
if [ "$string" = "abc e" ]             //比较字符串是否相等,相等则执行相应操作      等号 左右一定要加空格
then
    echo "成功"
fi
echo "end"
3、
read score
if [ $score -ge 80  -a $score -le 100 ]
then
    echo "A"
else if [ $score -ge 60 -a $score -lt 80 ]
then 
    echo "B"
else 
    echo "NO PASS"
fi
fi
4、
string=abc
test $string = "quit"      
[ $string = "quit" ]         # [的右边和]的左边都至少有一个空格
echo $?

test $string != "quit"                 # 判断字符串是否相等时,等号左右一定要加空格
echo $?

test -z $string            #判断字符串长度是否为0
echo $?

test -n $string            #判断字符串长度是否部位0
echo $?
5、shell函数 
function check_user()
{
    exist=`cat /etc/passwd | cut -d ':' -f 1 | grep "^$1$" | wc -l`

    if [ $exist -eq 0 ]
    then
        return 0              // 查询输入的用户名是否存在,存在返回num值,否则返回0
    else 
        num=`cat /etc/passwd | cut -d ':' -f 1 | grep "^$1$" -n | cut -d ':' -f 1`
        return $num
    fi
}
function show_user()
{
    username=`cat /etc/passwd | head -$1 | tail -1 | cut -d ':' -f 1`
    uid=`cat /etc/passwd | head -$1 | tail -1 | cut -d ':' -f 3`
    gid=`cat /etc/passwd | head -$1 | tail -1 | cut -d ':' -f 4`                     //在上面函数判断用户名存在的条件下,输出用户名的详细信息
                                                                                                                  
    echo $username           
    echo $uid
    echo $gid
}
while :
do
    echo -n "请输入用户名:"
    read uname
    if [ $uname = "quit" ]
    then
        exit
    fi
    check_user $uname                          //主函数部分
    value=$?
    if [ $value -eq 0 ]
    then
        echo "用户不存在,重新输入"
        continue
    fi
    show_user $value
done
6、 从终端读入一个字符串,判断字符串。。。。。。
echo -n "请输入文件夹:"
read fname         #/home/linux/abc
if [ ! -e $fname ]
then 
    echo "文件不存在"
    exit
fi
if  [ -d $fname ]
then
    list=`ls $fname`
    cd $fname
    for var in $list
    do
        if [ -d $var ]  #/home/linux/abc/$var
        then 
            cp $var ~/dir -a
        fi
        if [ -f $var ]
        then 
            cp $var ~/file
        fi
    done
else 
    echo "不是目录"
    exit
fi


猜你喜欢

转载自blog.csdn.net/qq_33575901/article/details/80980280