Shell多分支if语句
来源:互联网 发布:工业电脑如何编程 编辑:程序博客网 时间:2024/06/17 01:51
一 语法
if [ 条件判断式 ]
then
当条件判断式1成立时,执行程序1
elif[ 条件判断式2 ]
then
当条件判断式2成立时,执行程序2
省略更多条件
else
当所有条件都不成立时,最后执行程序
fi
二 实现计算器
#!/bin/bash
read -t 30 -p "please input num1:" num1
read -t 30 -p "please input num2:" num2
read -t 30 -p "please input a 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
sum=$(($num1 + $num2))
elif [ "$ope" == "-" ]
then
sum=$(($num1 - $num2))
elif [ "$ope" == "*" ]
then
sum=$(($num1 * $num2))
elif [ "$ope" == "/" ]
then
sum=$(($num1 / $num2))
else
echo "Please enter a valid symbol"
exit 10
fi
else
echo "please input a num"
exit 11
fi
else
echo "please input a content:"
exit 12
fi
echo "$num1 $ope $num2 : $sum"
三 测试
please input num1:re
please input num2:23
please input a operator:1
please input a num
[root@localhost shell]# echo $?
11
[root@localhost shell]# ./shell5.sh
please input num1:
please input num2:
please input a operator:
please input a content:
[root@localhost shell]# echo $?
12
[root@localhost shell]# ./shell5.sh
please input num1:12
please input num2:23
please input a operator:gf
Please enter a valid symbol
[root@localhost shell]# echo $?
10
[root@localhost shell]# ./shell5.sh
please input num1:32
please input num2:12
please input a operator:-
32 - 12 : 20
[root@localhost shell]# ./shell5.sh
please input num1:76
please input num2:45
please input a operator:*
76 * 45 : 3420
[root@localhost shell]# ./shell5.sh
please input num1:87
please input num2:56
please input a operator:/
87 / 56 : 1
[root@localhost shell]# ./shell5.sh
please input num1:45
please input num2:23
please input a operator:+
45 + 23 : 68
四 判断用户输入的是什么文件
#!/bin/bash
read -t 30 -p "please input a file name:" file
if [ -z "$file" ]
then
echo "qing shuru neirong"
exit 11
elif [ ! -e "$file" ]
then
echo "qing shuru wenjianming"
exit 12
elif [ -f "$file" ]
then
echo "$file is a regular file"
elif [ -d "$file" ]
then
echo "$file is a mulu"
else
echo "$file is another file"
fi
阅读全文
0 0
- Shell多分支if语句
- shell单分支if语句
- shell双分支if语句
- if 多分支语句区别
- Shell编程中if-elif-else条件分支语句测试
- Shell多分支case语句
- if分支语句优化
- if分支语句
- 单分支 if 语句
- 基本if分支语句
- if选择分支语句
- 分支中if语句
- Swift分支语句--if语句
- 用于多分支的条件语句(if-else语句)
- if/else 分支控制语句
- Java分支结构-if语句
- 2.2 分支结构-if语句
- 【C语言】if分支语句
- CSS总结
- 关于写sdk的时候,避免jar冲突的一些小见解
- maven自动创建目录骨架
- 上海下一个独角兽公司将锁定!据说福利秒杀顶级科技巨头
- maven中的坐标和仓库
- Shell多分支if语句
- Shell多分支case语句
- 1027修改打印沙漏(20) for内循环 分情况 第一输出空格 第二输出符号
- Mac下用vue-cli+webpack+bootstrap实现一个todo-list(一)
- Linux压缩命令实用版
- 构造,析构,复制构造,重载=,和自动创建无名变量的问题(习题)
- TSPL4/3.3-Continuations
- maven中的生命周期和插件
- 九度1015