shell脚本之if语句
来源:互联网 发布:休闲食品网络市场调查 编辑:程序博客网 时间:2024/06/04 18:14
测试
到目前为止,经常与 if 一块使用的命令是 test。这个 test 命令执行各种各样的检查与比较。 它有两种等价模式:
test expression
比较流行的格式是:
[ expression ]
这里的 expression 是一个表达式,其执行结果是 true 或者是 false。当表达式为真时,这个 test 命令返回一个零 退出状态,当表达式为假时,test 命令退出状态为1。
例如:
x=5
if test $x=5;then
echo "x equals 5"
else
echo "x is not equals 5"
fi
if [ $x=5 ];then //[ 和]的左右必须有空格
echo "x equals 5"
else
echo "x is not equals 5"
fi
文件表达式
以下表达式被用来计算文件状态:
这里我们有一个脚本说明了一些文件表达式:
#!/bin/bash# test-file: Evaluate the status of a fileFILE=~/.bashrcif [ -e "$FILE" ]; then if [ -f "$FILE" ]; then echo "$FILE is a regular file." fi if [ -d "$FILE" ]; then echo "$FILE is a directory." fi if [ -r "$FILE" ]; then echo "$FILE is readable." fi if [ -w "$FILE" ]; then echo "$FILE is writable." fi if [ -x "$FILE" ]; then echo "$FILE is executable/searchable." fielse echo "$FILE does not exist" exit 1fiexit
字符串表达式
以下表达式用来计算字符串:
string1 = string2
string1 == string2
string1 和 string2 相同. 单或双等号都可以,不过双等号更受欢迎。string1 != string2string1 和 string2 不相同。string1 > string2sting1 排列在 string2 之后。string1 < string2string1 排列在 string2 之前。#!/bin/bash# test-string: evaluate the value of a stringANSWER=maybeif [ -z "$ANSWER" ]; then echo "There is no answer." >&2 exit 1fiif [ "$ANSWER" = "yes" ]; then echo "The answer is YES."elif [ "$ANSWER" = "no" ]; then echo "The answer is NO."elif [ "$ANSWER" = "maybe" ]; then echo "The answer is MAYBE."else echo "The answer is UNKNOWN."fi
整型表达式
下面的表达式用于整数:
这里是一个演示以上表达式用法的脚本:
#!/bin/bash# test-integer: evaluate the value of an integer.INT=-5if [ -z "$INT" ]; then echo "INT is empty." >&2 exit 1fiif [ $INT -eq 0 ]; then echo "INT is zero."else if [ $INT -lt 0 ]; then echo "INT is negative." else echo "INT is positive." fi if [ $((INT % 2)) -eq 0 ]; then echo "INT is even." else echo "INT is odd." fifi
这个脚本中有趣的地方是怎样来确定一个整数是偶数还是奇数。通过用模数2对数字执行求模操作, 就是用数字来除以2,并返回余数,从而知道数字是偶数还是奇数。
if [ ! \( $INT -ge $MIN_VAL -a $INT -le $MAX_VAL \) ]; then echo "$INT is outside $MIN_VAL to $MAX_VAL."else echo "$INT is in range."fi
因为 test 使用的所有的表达式和操作符都被 shell 看作是命令参数, 对于 bash 有特殊含义的字符,比如说 <,>,(,和 ),必须引起来或者是转义。
1 0
- shell脚本之if语句
- shell脚本:if语句
- shell 脚本 if 语句
- shell 脚本if语句
- SHELL脚本if语句
- SHELL脚本if语句
- shell脚本编程之for语句、if语句使用介绍
- Linux-shell脚本-if语句/case语句
- linux shell脚本之if
- shell 脚本之if判断
- shell之if简化语句
- shell 编程之 if 语句
- 脚本乐园 shell编程if语句
- shell脚本里的if语句学习
- shell脚本中if语句的用法
- Shell脚本基础5-if-then语句
- shell脚本;if语句测试ping
- shell脚本之条件语句if和分支语句case...esac【shell脚本的学习笔记三】
- 语音学习笔记10------如何利用Deep CNN大幅提升识别准确率?
- 计算机硬件软件dos基础常识
- CentOS配置hadoop
- 进入某个目录需要什么权限
- 北邮OJ-97. 二叉排序树-12计院上机C
- shell脚本之if语句
- 小记SpringBoot使用方法
- JAVA简介
- 利用tensorflow的upgrade.py将之前的代码自动升级为1.0版本的代码
- C语言 · 阿尔法乘积
- 面向对象的哲学。举例:小明被撞了,智商一百早上好。智商不好,乱说
- 一分钟教你知道乐观锁和悲观锁的区别
- VirtualBox is not installed. Please re-run the Toolbox Installer and try again.
- 《Python爬虫学习系列教程》学习笔记