In linux, we often deal with file directories, which involves judging whether the file or directory is empty, writable, etc.
- [ -f file ] Determine whether it is a normal file and exists
[root@lijie-01 ~]# cat file1.sh
#!/bin/bash
f=/root/lijie.txt
if [ -f $f ]
then
echo $f exist
else
touch $f
fi
[root@lijie-01 ~]#
Then we look at the execution process
- [ -d file ] Determine whether it is a directory and exists
[root@lijie-01 ~]# cat !$
cat file2.sh
#!/bin/bash
f=/root/lijie.txt
if [ -d $f ]
then
echo $f exist
else
touch $f //注意touch即可创建文件也可创建目录,如果文件或目录存在,touch就会修改文件或目录的三个time: mtime ctime atime
fi
[root@lijie-01 ~]#
View the execution process
- [ -e file ] Determine if a file or directory exists
- [ -r file ] Determine if the file is readable
[root@lijie-01 ~]# cat !$
cat file2.sh
#!/bin/bash
f=/root/lijie.txt
if [ -r $f ]
then
echo $f readable
fi
[root@lijie-01 ~]#
The execution process is as follows
- [ -w file ] Determine if the file is writable
[root@lijie-01 ~]# cat file2.sh
#!/bin/bash
f=/root/lijie.txt
if [ -w $f ]
then
echo $f writeable
fi
[root@lijie-01 ~]#
The execution process is as follows
- [ -x file ] Determine if the file is executable
[root@lijie-01 ~]# ll lijie.txt
-rw-r--r--. 1 root root 0 4月 19 06:14 lijie.txt
[root@lijie-01 ~]# cat file2.sh
#!/bin/bash
f=/root/lijie.txt
if [ -x $f ]
then
echo $f exeable
fi
[root@lijie-01 ~]#
The execution process is as follows
In the above figure, since we did not give the file execution permission or set the else statement, no results were returned.
In fact, the judgment of whether a file is readable, writable, and executable is based on the current user. The following Code block is a common method to
determine whether a file exists, and if it exists, delete the file
#!/bin/bash
f=/root/lijie.txt
# [ -f $f] && rm -f $f //这种方式的效果等同于下面四行的效果
if [ -f $f ]
then
rm -f $f
fi
Check if a file exists, and create it if it doesn't
#!/bin/bash
f=/root/lijie.txt
# [ ! -f $f ] || touch $f //这种方式的效果等同于下面四行的效果
if [ ! -f $f ]
then
touch $f
fi