shell中的文件目錄屬性判斷

在linux中,咱們常常會跟文件目錄打交道,這就涉及到判斷這個文件或目錄是否是空、是否可寫等狀況linux

  • [ -f file ]判斷是不是普通文件,且存在
[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 ~]#

而後咱們來查看執行過程
輸入圖片說明bash

  • [ -d file ] 判斷是不是目錄,且存在
[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 ~]#

查看執行過程
輸入圖片說明code

  • [ -e file ] 判斷文件或目錄是否存在
  • [ -r file ] 判斷文件是否可讀
[root@lijie-01 ~]# cat !$
cat file2.sh
#!/bin/bash
f=/root/lijie.txt
if [ -r $f ]
then 
  echo $f readable
fi
[root@lijie-01 ~]#

執行過程以下
輸入圖片說明圖片

  • [ -w file ] 判斷文件是否可寫
[root@lijie-01 ~]# cat file2.sh
#!/bin/bash
f=/root/lijie.txt
if [ -w $f ]
then 
  echo $f writeable
fi
[root@lijie-01 ~]#

執行過程以下
輸入圖片說明it

  • [ -x file ] 判斷文件是否可執行
[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 ~]#

執行過程以下
輸入圖片說明
上圖中,因爲咱們沒有給這個文件執行權限,也沒有設置else語句,所以沒有反饋任何結果
實際上,判斷一個文件是否可讀可寫可執行,是基於當前用戶來判斷的,如下代碼塊爲經常使用方法
判斷一個文件是否存在,若是存在則刪除這個文件file

#!/bin/bash
f=/root/lijie.txt
# [ -f $f] && rm -f $f   //這種方式的效果等同於下面四行的效果
if [ -f $f ]
then
  rm -f $f
fi

判斷一個文件是否存在,若是不存在則建立這個文件權限

#!/bin/bash  
f=/root/lijie.txt
# [ ! -f $f ] || touch $f   //這種方式的效果等同於下面四行的效果
if [ ! -f $f ]
then
  touch $f
fi
相關文章
相關標籤/搜索