首页 > 系统服务 > 详细

Shell编程 之 if语句2

时间:2017-02-12 15:51:04      阅读:180      评论:0      收藏:0      [点我收藏+]

4. 多分支 if 语句

  4.1 语句结构

    技术分享

  4.2 简易计算器

#!/bin/bash

read -t 30 -p "input number1: " num1
read -t 30 -p "input number2: " num2
read -t 30 -p "input an operator: " ope

if [ -n "$num1" -a -n "$num2" -a -n "$ope" ]
        then
                test1=$(echo $num1 | sed ‘s/[0-9]//g‘)
                test2=$(echo $num2 | sed ‘s/[0-9]//g‘)

        if [ -z "$test1" -a -z "$test2" ]
                then
                        if [ "$ope" == ‘+‘ ]
                                then
                                        res=$(( $num1 + $num2))
                        elif [ "$ope" == ‘-‘ ]
                                then
                                        res=$(( $num1 - $num2))
                        elif [ "$ope" == ‘*‘ ]
                                then
                                        res=$(( $num1 * $num2))
                        elif [ "$ope" == ‘/‘ ]
                                then
                                        res=$(( $num1 / $num2))
                        else
                                echo "invalid operator"
                                exit 10
                        fi
        else
                echo "invalid number"
                exit 11
        fi
else
        echo "no number inputed"
        exit 12
fi

echo "$num1 $ope $num2 = $res"

  4.5 判断用户输入的是什么文件

    tips:运行中输错内容,按 ctrl + backspace 进行删除

#!/bin/bash

read -t 30 -p "input a filename: " file

if [ -z "$file" ]
        then
                echo "no inputs"
                exit 11
elif [ ! -e "$file" ]
        then
                echo "$file is not a file"
                exit 22
elif [ -f "$file" ]
        then
                echo "$file is a regular file"
elif [ -d "$file" ]
        then
                echo "$file is a directory"
else
        echo "$file is a specific file"
fi
~                                                                                     
~                                                                                     
~                                                                                                                                                                         
"if6.sh" 21L, 331C

  

Shell编程 之 if语句2

原文:http://www.cnblogs.com/wnzhong/p/6390960.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!