重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
這篇文章主要介紹了如何使用Bash Shell檢查文件是否存在,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
可以用如下的命令來進行檢查:
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
感謝你能夠認真閱讀完這篇文章,希望小編分享的“如何使用Bash Shell檢查文件是否存在”這篇文章對大家有幫助,同時也希望大家多多支持創新互聯網站建設公司,,關注創新互聯行業資訊頻道,更多相關知識等著你來學習!