Linux命令之test

test 表示判断的命令: test  -e demo.txt

-e • 该文件是否存在? • !!!
-f • 该文件是否存在且为文件(file)? • !!!
-d • 该文件名是否存在且为目录(directory)? • !!!  

-b • 该文件是否存在且为一个 block • device • 装置?
-c • 该文件是否存在且为一个 character device • 装置? •
-S 该文件是否存在且为一个 Socket • 文件? •
-p • 该文件是否存在且为一个 FIFO • (pipe) • 文件? •
-L • 该文件是否存在且为一个链接文件? •
前面三个是使用最多的 判断是否是文件  是否是目录  是否存在

下面是进行判断文件的权限的操作了

-r 检查该文件是否存在且具有可读的权限? •
-w • 检查该文件是否存在且具有可写的权限? •
-x • 检查该文件是否存在且具有可执行的权限? •

-s • 检查该文件是否存在且为非空文件?
-u • 检查该文件名是否存在且具有SUID的属性? •
-g • 检查该文件名是否存在且具有SGID的属性? •
 

test 判断字符串的操作

test -z •string 判断字符串是否为空?若string为空字符串,则为true
test -n string 判断字符串是否非空?若string为空字符串,则为 false
test str1 • = • str2 或==• 判断str1是否等于str2,若相等,则返回
true •
test • str1 • != • str2 • 判断str1是否不等于str2,若相等,则返回 false
 

shell的案例:

编写shell脚本,实现判断:
• 先给予提示:please input a filename:
• 1.是否输入了文件名,如果为空提示:you must input
a filename,并结束脚本
• 2.判断文件是否存在?不存在则结束脚本
• 3.判断文件类型以及统计文件都有哪些权限
• 4.输出文件类型和文件所有的权限。
 

#!/bin/bash

echo -e "please input a filename,I will check it isn't exist,type and permission.\n"
read -p "input a filename:" filename
#1.check filename is not null ! ""
test -z $filename&&echo "you must input a filename."&&exit 1
#2.check file is exist?no exist end program
test ! -e $filename&&echo "the filename $filename not exist"&&exit 2
#3.check file type and permission
test -f $filename&&filetype="file"
test -d $filename&&filetype="directory“
test -r $filename&&perm="readable"
test -w $filename&&perm="${perm},writable"
test -x $filename&&perm="${perm},executable"
#4.show file message
echo "the filename:$filename is a $filetype"
echo "and the permisssions are:$perm"

exit 0
 

两个文件之间比较


-nt 判断file1 • 是否比 file2 • 新
-ot 判断file1 • 是否比 file2 • 旧
-ef 判断两个文件是否为同一个文件
 

  判断符号[](基本跟test相同) !!!
 [ ]  脚本范例 (注意[]和脚本之间保留空格)
 ==和!=用于比较字符串;
 整数比较只能使用-eq,-gt,ge,lt,le这种形式  整数比较操作
 [ ]中的逻辑与和逻辑或使用-a 和-o 表示
 &&、 ||、 <和> 操作符如果出现在[ ]结构中的话,会报错。
下面给出一个案例:

#!/bin/bash

read -p "please input Y/N" yn

[  "$yn" ==  "Y"  -o  "$yn" == "y"  ]&&echo "chioces Yes"&& exit 0

[ “$yn” == “N” -o "$yn" == "n"  ]&&echo "choices No"&& exit 0

猜你喜欢

转载自blog.csdn.net/tryll/article/details/86592869