0
点赞
收藏
分享

微信扫一扫

shell条件表达式

条件表达式

条件表达式,我们非常的常用,可以说,任何编程语言,都离不开条件表达式,但是每种变成语言的写法都不太一 样,在shell中,有一种独特的写法。

[ 条件 ] ## 不支持 > < 支持:-eq -le -ne
[[ 条件 ]] ## 支持 > < -eq -le -ne
test 条件 ## 都支持 命令行使用test

条件表达式的选项

判断普通文件 -f file

-f:判断文件是否存在
[root@web01 ~]# test -f /tmp/1.txt
[root@web01 ~]# echo $?
1

[root@web01 ~]# test -f /tmp/1.txt && echo '存在'|| echo '不存在'
不存在
[root@web01 tmp]# [ -f /tmp/1.txt ] && echo '存在' || echo '不存在'
不存在
[root@web01 tmp]# [[ -f /tmp/1.txt ]] && echo '存在' || echo '不存在'
不存在

判断目录 -d directory

[root@web01 tmp]# test -d /tmp/a
[root@web01 tmp]# echo $?
0

[root@web01 tmp]# test -d /tmp/a && echo '存在' || echo '不存在'
存在
[root@web01 tmp]# [ -d /tmp/a ] && echo '存在' || echo '不存在'
存在
[root@web01 tmp]# [[ -d /tmp/a ]] && echo '存在' || echo '不存在'
存在

判断文件-e exists

既可以判断文件也可以判断目录
[root@web01 tmp]# test -e /tmp/1.txt && echo '存在' || echo '不存在'
不存在
[root@web01 tmp]# test -e /tmp/a && echo '存在' || echo '不存在'
存在

判断文件有没有读取权限 -r read

[root@web01 tmp]# test -r /tmp/a && echo '可读' || echo '不可读'
可读

判断文件有没有写入权限 -w write

[root@web01 tmp]# test -e /tmp/a && echo '可写' || echo '不可写'
可写

判断文件有没有执行权限 -x execute

[root@web01 tmp]# test -x /tmp/a && echo '可执行' || echo '不可执行'
可执行

判断文件有没有内容-s size

[root@web01 tmp]# test -s /tmp/1.txt && echo '有内容' || echo '文件为空'
文件为空
[root@web01 tmp]# test -s /tmp/a && echo '有内容' || echo '文件为空'
有内容

判断文件是否是一个软链接 -L link

[root@web01 tmp]# test -L /bin && echo '是软链接' || echo '不是软连接'
是软链接
[root@web01 tmp]# test -L /tmp && echo '是软链接' || echo '不是软连接'
不是软连接

对比两个文件的新旧 -nt newer than

[root@web01 tmp]# test /tmp/1.txt -nt /tmp/2.txt && echo '1.txt比2.txt新' || echo '2.txt比1.txt新'
2.txt比1.txt新

[root@web01 tmp]# echo '123' > 1.txt
[root@web01 tmp]# test /tmp/1.txt -nt /tmp/2.txt && echo '1.txt比2.txt新' || echo '2.txt比1.txt新'
1.txt比2.txt新

对比两个文件的新旧 -ot oldder than

[root@web01 tmp]# test /tmp/1.txt -ot /tmp/2.txt && echo '1.txt比2.txt老' || echo '2.txt比1.txt老'
2.txt比1.txt老
[root@web01 tmp]# echo '123' > 2.txt
[root@web01 tmp]# test /tmp/1.txt -ot /tmp/2.txt && echo '1.txt比2.txt老' || echo '2.txt比1.txt老'
1.txt比2.txt老

脚本作业:计算器

1.首先要传递2个参数(数字)

2.传少了报错

报错信息:至少传递两个整数...

3.传的不是数字报错

报错信息:请输入两个整数,不能是字母或特殊符号...

4.计算出传递两个数字的

+

-

*

/

%

#!/bin/bash

# File Name: __calculator.sh__
# Version: __v1.1__
# Author: __yjt__
# Mail: __1781811351@qq.com__


num1=$1
num2=$2

if [ $# -ne 2 ];then
echo '请输入参数为2个的整数'
else
expr $num1 + $num2 &>/dev/null
[ $? -ne 0 ] && echo '请输入数字...'
expr $num1 + $num2 2>/dev/null
expr $num1 - $num2 2>/dev/null
expr $num1 \* $num2 2>/dev/null
expr $num1 / $num2 2>/dev/null
expr $num1 % $num2 2>/dev/null
fi

举报

相关推荐

0 条评论