1. 编写函数,实现打印绿色OK和红色FAILED 判断是否有参数,存在为Ok,不存在为FAILED [root@template shellScript]# cat ex1.sh# 编写函数,实现打印绿色OK和红色FAILED 判断是否有参数,存在为Ok,不
[root@template shellScript]# cat ex1.sh
# 编写函数,实现打印绿色OK和红色FAILED 判断是否有参数,存在为Ok,不存在为FAILED
#!/bin/bash
fun(){
if [ $# -ne 0 ]
then
echo -e "\033[32m OK \033[0m"
else
echo -e "\033[31m FAILED \033[0m"
fi
}
read -p "plz input sth..." str
fun $str
[root@template shellScript]# ./ex1.sh
plz input sth...1qw11d1d
OK
[root@template shellScript]# ./ex1.sh
plz input sth...
FAILED
运行效果图:
[root@template shellScript]# cat ex2.sh
# 编写函数,实现判断是否无位置参数,如无参数,提示错误
#!/bin/bash
fun() {
if [ $# -eq 0 ]
then
echo "无位置参数"
else
echo "位置参数为$@"
fi
}
read -p "plz input sth..." str
fun $str
运行截图:
# 此方法不能比较负数的大小
[root@template shellScript]# cat ex3.sh
# 编写函数实现两个数字做为参数,返回最大值
#!/bin/bash
fun(){
# 判断输入是否是数字
if [[ $a =~ ^[0-9]*$ ]] && [[ $b =~ ^[0-9]*$ ]]
then
# 比较大小
if [ $a -gt $b ]
then
echo "$a > $b"
elif [ $a -lt $b ]
then
echo "$a < $b"
else
echo "$a = $b"
fi
else
echo "请输入俩个数字!!!"
fi
}
# 输入负数也可以比较大小
# read -p "plz input two num:" a b
read -p "plz input num1:" a
read -p "plz input num2:" b
fun $a $b
测试截图:
方式二:
[root@template shellScript]# cat ./ex3_2.sh
#!/bin/bash
read -p "please input two number:" a b
fun(){
[ -z "$a" -o -z "$b" ] && {
echo "please input 'two' number"
exit 1
}
expr $a + 10 &>/dev/null
return_a=$?
expr $b + 10 &>/dev/null
return_b=$?
[ "$return_a" -eq 0 -a "$return_b" -eq 0 ] || {
echo "please input two 'number'"
exit 2
}
[ "$a" -lt "$b" ] && {
echo "$a < $b"
exit 0
}
[ "$a" -eq "$b" ] && {
echo "$a = $b"
exit 0
}
[ "$a" -gt "$b" ] && {
echo "$a > $b"
exit 0
}
}
fun $a $b
运行截图:
原文链接:https://www.cnblogs.com/sre-chan/p/17278868.html