20.6 if文件目錄屬性判斷

if文件目錄屬性判斷

if 判斷文件、目錄屬性

  • [ -f file ]判斷是不是普通文件,且存在
  • [ -d file ] 判斷是不是目錄,且存在
  • [ -e file ] 判斷文件或目錄是否存在
  • [ -r file ] 判斷文件是否可讀
  • [ -w file ] 判斷文件是否可寫
  • [ -x file ] 判斷文件是否可執行

文件目錄屬性判斷

if 判斷文件、目錄屬性

  • [ -f file ]判斷是不是普通文件,且存在
[root@xuexi-001 shell]# vi file1.sh
#!/bin/bash
f="/tmp/aminglinux"
if [ -f $f ]
then
        echo $f exist
else 
        touch $f
fi
[root@xuexi-001 shell]# cat file1.sh 
#!/bin/bash
f="/tmp/aminglinux"
if [ -f $f ]
then
	echo $f exist
else 
	touch $f
fi

[root@xuexi-001 shell]# chmod +x file1.sh
[root@xuexi-001 shell]# sh file1.sh   #執行完後這個文件已經建立
[root@xuexi-001 shell]# ls /tmp/
aminglinux

[root@xuexi-001 shell]# sh -x file1.sh 
+ f=/tmp/aminglinux
+ '[' -f /tmp/aminglinux ']'
+ echo /tmp/aminglinux exist
/tmp/aminglinux test
[root@xuexi-001 shell]# sh file1.sh 
/tmp/aminglinux test

if 判斷文件、目錄屬性

  • [ -d file ] 判斷是不是目錄,且存在
[root@xuexi-001 shell]# sh -x file2.sh 
+ f=/tmp/aminglinux1
+ '[' -d /tmp/aminglinux1 ']'
+ echo /tmp/aminglinux1 exist
/tmp/aminglinux1 exist
[root@xuexi-001 shell]# ls /tmp/aminglinux
aminglinux   aminglinux1/ 
[root@xuexi-001 shell]# ls /tmp/aminglinux
/tmp/aminglinux
[root@xuexi-001 shell]# ls /tmp/
aminglinux
aminglinux1

if 判斷文件、目錄屬性

  • [ -e file ] 判斷文件或目錄是否存在

目錄和文件均可以touch 的,touch的目的是 若是這個文件或目錄不存在,它會建立這個文件,若是這個文件或目錄存在了,在touch 就會更改這個文件的三個 timelinux

[root@xuexi-001 shell]# vi file2.sh 

#!/bin/bash
f="/tmp/aminglinux2"
if [ -e $f ]
then
        echo $f exist
else
        touch $f
fi
[root@xuexi-001 shell]# sh file2.sh 
[root@xuexi-001 shell]# sh -x file2.sh 
+ f=/tmp/aminglinux2
+ '[' -e /tmp/aminglinux2 ']'
+ echo /tmp/aminglinux2 exist
/tmp/aminglinux2 exist
[root@xuexi-001 shell]# ls /tmp/
aminglinux
aminglinux1
aminglinux2

if 判斷文件、目錄屬性

  • [ -r file ] 判斷文件是否可讀
[root@xuexi-001 shell]# vi file2.sh 

#!/bin/bash
f="/tmp/aminglinux2"
if [ -r $f ]
then
        echo $f readable
fi
[root@xuexi-001 shell]# sh file2.sh 
/tmp/aminglinux2 readable
   會看到文件可讀的

if 判斷文件、目錄屬性

  • [ -w file ] 判斷文件是否可寫

去判斷是否刻度可寫,就判斷執行shell腳本的當前用戶shell

[root@xuexi-001 shell]# vi file2.sh 

#!/bin/bash
f="/tmp/aminglinux2"
if [ -w $f ]
then
        echo $f writeable
fi
[root@xuexi-001 shell]# sh file2.sh 
/tmp/aminglinux2 writeable

if 判斷文件、目錄屬性

  • [ -x file ] 判斷文件是否可執行
[root@xuexi-001 shell]# vi file2.sh 

#!/bin/bash
f="/tmp/aminglinux2"
if [ -x $f ]
then
        echo $f exeable
fi
[root@xuexi-001 shell]# sh file2.sh 
[root@xuexi-001 shell]# 
由於不能夠執行,因此沒有任何輸出

經常使用案例

  • 而且 &&
f="/tmp/aminglinux2"
[ -f $f ] && rm -f $f     //前一條命令執行成功纔會繼續執行以後的命令
等同於下面的表達方式
if [ -f $f ]     
then
      rm -rf $f
fi
  • 或者 ||
f="/tmp/aminglinux2"
[ -f $f ] || touch $f    //前面命令不成功時,執行後面的命令
if [ ! -f $f ]        //  「!」表示了若是這條命令不成功,就往下執行
then
      touch $f
fi
相關文章
相關標籤/搜索