方法1:传参

#!/bin/bash

##############################################################

# File Name: compare1.sh

# Version: V7.4

# Author: feng yu

# Organization: https://blog.51cto.com/13520761

# Created Time : 2018-03-26 17:22:20

# Description:

##############################################################

[ $# -ne 2 ] && echo "请输入2个参数" && exit 2        ---参数个数不等于2时,提示请输入2个参数,并退出


expr $1 + 1 &>/dev/null

[ $? -eq 2 ] && echo "请输入整数" && exit 2             ---判断第一个参数是否为整数,不是整数,提示请输入整数,并退出


expr $2 + 1 &>/dev/null

[ $? -eq 2 ] && echo "请输入整数" && exit 2            ---判断第二个参数是否为整数,不是整数,提示请输入整数,并退出


[ $1 -eq $2 ] && echo "$1 = $2"         

[ $1 -lt $2 ] && echo "$1 < $2"            

[ $1 -gt $2 ] && echo "$1 > $2"


方法2:传参(if表达式)

#!/bin/bash

##############################################################

# File Name: compare.sh

# Version: V7.4

# Author: feng yu

# Organization: https://blog.51cto.com/13520761

# Created Time : 2018-03-26 16:20:43

# Description:

##############################################################

if ! [ $# -eq 2 ];then

    echo "请输入2个参数"

    exit

fi


expr $1 + 1 &>/dev/null

if [ $? -eq 2 ];then

    echo "请输入整数"

    exit

fi


expr $2 + 1 &>/dev/null

if [ $? -eq 2 ];then

    echo "请输入整数"

    exit

fi


if [ $1 -eq $2 ];then

    echo "$1 = $2"

elif [ $1 -lt $2 ];then

    echo "$1 < $2"

elif [ $1 -gt $2 ];then

    echo "$1 > $2"

fi


方法3:read读入

#!/bin/bash

##############################################################

# File Name: compare2.sh

# Version: V7.4

# Author: feng yu

# Organization: https://blog.51cto.com/13520761

# Created Time : 2018-03-26 18:20:14

# Description:

##############################################################

read -p "请输入整数:" num1


expr $num1 + 1 &> /dev/null

[ $? -eq 2 ] && echo "请输入整数" && exit 2

[ -z "$num1" ] && echo "请输入一个整数" && exit 2


read -p "请输入整数:" num2

expr $num2 + 1 &> /dev/null

[ $? -eq 2 ] && echo "请输入整数" && exit 2   

[ -z "$num2" ] && echo "请输入一个整数" && exit 2 

 

[ $num1 -eq $num2 ] && echo "$num1 = $num2"

[ $num1 -gt $num2 ] && echo "$num1 > $num2"

[ $num1 -lt $num2 ] && echo "$num1 < $num2"


方法4:read读入(if表达式)

#!/bin/bash

##############################################################

# File Name: compare2.sh

# Version: V7.4

# Author: feng yu

# Organization: https://blog.51cto.com/13520761

# Created Time : 2018-03-26 18:20:14

# Description:

##############################################################

read -p "请输入整数:" num1


expr $num1 + 1 &> /dev/null

if [ $? -eq 2 ];then

    echo "请输入整数"

    exit 2

fi

if [ -z "$num1" ];then

    echo "请输入一个整数"

    exit 2

fi


read -p "请输入整数:" num2


expr $num2 + 1 &> /dev/null

if [ $? -eq 2 ];then

    echo "请输入整数"

    exit 2

fi

if [ -z "$num2" ];then

    echo "请输入一个整数" 

    exit 2

fi


if [ $num1 -eq $num2 ];then

    echo "$num1 = $num2"

elif [ $num1 -gt $num2 ];then

    echo "$num1 > $num2"

elif [ $num1 -lt $num2 ];then

    echo "$num1 < $num2"

fi