if文件目录属性判断
- if 判断文件、目录属性
- [ -f file ]判断是不是普通文件,且存在
- [ -d file ] 判断是不是目录,且存在
- [ -e file ] 判断文件或目录是否存在
- [ -r file ] 判断文件是否可读
- [ -w file ] 判断文件是否可写
- [ -x file ] 判断文件是否可执行
文件目录属性判断
[root@hf-01 shell]# vim file1.sh
[root@hf-01 shell]# cat file1.sh
#! /bin/bash
f="/tmp/hanfeng"
if [ -f $f ]
then
echo $f exist
else
touch $f
fi
[root@hf-01 shell]# sh -x file1.sh 第一次执行,会建立该文件
+ f=/tmp/hanfeng
+ '[' -f /tmp/hanfeng ']'
+ touch /tmp/hanfeng
[root@hf-01 shell]# sh -x file1.sh 第二次执行,会提示该文件已存在
+ f=/tmp/hanfeng
+ '[' -f /tmp/hanfeng ']'
+ echo /tmp/hanfeng exist
/tmp/hanfeng exist
[root@hf-01 shell]#
[root@hf-01 shell]# vim file2.sh
[root@hf-01 shell]# cat !$
cat file2.sh
#! /bin/bash
f="/tmp/hanfeng"
if [ -d $f ]
then
echo $f exist
else
mkdir $f
fi
[root@hf-01 shell]# sh -x file2.sh
+ f=/tmp/hanfeng
+ '[' -d /tmp/hanfeng ']'
+ mkdir /tmp/hanfeng
[root@hf-01 shell]#
- if 判断文件、目录属性
- 目录和文件均可以touch 的,touch的目的是 若是这个文件或目录不存在,它会建立这个文件,若是这个文件或目录存在了,在touch 就会更改这个文件的三个 time
[root@hf-01 shell]# vim file2.sh
[root@hf-01 shell]# sh -x file2.sh
+ f=/tmp/hanfeng
+ '[' -e /tmp/hanfeng ']'
+ echo /tmp/hanfeng exist
/tmp/hanfeng exist
[root@hf-01 shell]#
[root@hf-01 shell]# cat file2.sh
#! /bin/bash
f="/tmp/hanfeng"
if [ -r $f ]
then
echo $f readable
fi
[root@hf-01 shell]# sh file2.sh 会看到文件可读的
/tmp/hanfeng readable
[root@hf-01 shell]#
- if 判断文件、目录属性
- 去判断是否刻度可写,就判断执行shell脚本的当前用户
[root@hf-01 shell]# cat file2.sh
#! /bin/bash
f="/tmp/hanfeng"
if [ -w $f ]
then
echo $f writeable
fi
[root@hf-01 shell]# sh file2.sh
/tmp/hanfeng writeable
[root@hf-01 shell]#
[root@hf-01 shell]# cat file2.sh
#! /bin/bash
f="/tmp/hanfeng"
if [ -x $f ]
then
echo $f exeable
fi
[root@hf-01 shell]# sh file2.sh
/tmp/hanfeng exeable
经常使用案例
f="/tmp/aminglinux"
[ -f $f ] && rm -f $f //前一条命令执行成功才会继续执行以后的命令
等同于下面的表达方式
if [ -f $f ]
then
rm -rf $f
fi
f="/tmp/aminglinux"
[ -f $f ] || touch $f //前面命令不成功时,执行后面的命令
if [ ! -f $f ] // “!”表示了若是这条命令不成功,就往下执行
then
touch $f
fi