前言
大家在工作的時候可能常常會遇到這樣的需求,在類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"
較常見的用法,則是將test指令放置在if..else..fi條件判斷的條件表達式,然後在其中寫上不同的分支邏輯
Found
偵測檔案屬性的相關運算子如果檔案存在,且有對應的屬性,下列的運算子都會回傳true:
#!/bin/bash file="/etc/hosts" if [ -f "$file" ] then echo "$file found." else echo "$file not found." fi以上指令,從man test複製而來。 使用上述符號的方法一模一樣:
-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總結以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問可留言交流。 更多使用Bash Shell檢查檔案是否存在的方法相關文章請關注PHP中文網!