使用Bash Shell檢查文件是否存在的方法

轉載: https://www.jb51.net/article/102277.htm

 

前言

大家在工作的時候可能經常會遇到這樣的需求,在類Unix系統的Bash環境下,怎樣檢查文件是否存在呢?既然有需求,當然就有解決的辦法了,Shell中的test命令,可以用來檢測文件的類型或者比較數值是否相等,該命令也能用來檢查文件是否存在。

可以用如下的命令來進行檢查:

test -e filename
[ -e filename ]
  
test -f filename
[ -f filename ]

下面的命令,則使用Shell的條件表達式,判斷/etc/hosts文件是否存在:

[ -f /etc/hosts ] && echo "Found" || echo "Not found"

該組合命令會輸出以下內容:

Found

更常見的用法,則是將test命令放置在if..else..fi條件判斷的條件表達式,然後在其中寫上不同的分支邏輯

#!/bin/bash
file="/etc/hosts"
if [ -f "$file" ]
then
 echo "$file found."
else
 echo "$file not found."
fi

檢測文件屬性的相關操作符

如果文件存在,並且具有相應的屬性,如下的操作符都會返回true:

-b FILE
  FILE exists and is block special
-c FILE
  FILE exists and is character special
-d FILE
  FILE exists and is a directory
-e FILE
  FILE exists
-f FILE
  FILE exists and is a regular file
-g FILE
  FILE exists and is set-group-ID
-G FILE
  FILE exists and is owned by the effective group ID
-h FILE
  FILE exists and is a symbolic link (same as -L)
-k FILE
  FILE exists and has its sticky bit set
-L FILE
  FILE exists and is a symbolic link (same as -h)
-O FILE
  FILE exists and is owned by the effective user ID
-p FILE
  FILE exists and is a named pipe
-r FILE
  FILE exists and read permission is granted
-s FILE
  FILE exists and has a size greater than zero
-S FILE
  FILE exists and is a socket
-t FD file descriptor FD is opened on a terminal
-u FILE
  FILE exists and its set-user-ID bit is set
-w FILE
  FILE exists and write permission is granted
-x FILE
  FILE exists and execute (or search) permission is granted

以上命令,從man test複製而來。

使用上述符號的方法一模一樣:

if [ operator FileName ]
then
  echo "FileName - Found, take some action here"
else
 echo "FileName - Not found, take some action here"
fi

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可留言交流。

 

其他參考:

-e filename 如果 filename存在,則爲真
-d filename 如果 filename爲目錄,則爲真 
-f filename 如果 filename爲常規文件,則爲真
-L filename 如果 filename爲符號鏈接,則爲真
-r filename 如果 filename可讀,則爲真 
-w filename 如果 filename可寫,則爲真 
-x filename 如果 filename可執行,則爲真
-s filename 如果文件長度不爲0,則爲真
-h filename 如果文件是軟鏈接,則爲真
filename1 -nt filename2 如果 filename1比 filename2新,則爲真。
filename1 -ot filename2 如果 filename1比 filename2舊,則爲真。
-eq 等於
-ne 不等於
-gt 大於
-ge 大於等於
-lt 小於
-le 小於等於
至於!號那就是取非了唄!

參考鏈接:http://ask.zol.com.cn/x/4453967.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章