主頁(yè) > 知識(shí)庫(kù) > 使用Bash Shell檢查文件是否存在的方法

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

熱門(mén)標(biāo)簽:德陽(yáng)400電話申請(qǐng) 智能電銷(xiāo)機(jī)器人有用嗎 外呼電話系統(tǒng)怎么操作 商機(jī)地圖標(biāo)注 百度地圖標(biāo)注直線距離 怎么在百度地圖標(biāo)注公司的位置 天津電話外呼系統(tǒng)排名 鶴崗400電話申請(qǐng) 測(cè)繪地圖標(biāo)注名稱

前言

大家在工作的時(shí)候可能經(jīng)常會(huì)遇到這樣的需求,在類(lèi)Unix系統(tǒng)的Bash環(huán)境下,怎樣檢查文件是否存在呢?既然有需求,當(dāng)然就有解決的辦法了,Shell中的test命令,可以用來(lái)檢測(cè)文件的類(lèi)型或者比較數(shù)值是否相等,該命令也能用來(lái)檢查文件是否存在。

可以用如下的命令來(lái)進(jìn)行檢查:

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

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

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

該組合命令會(huì)輸出以下內(nèi)容:

Found

更常見(jiàn)的用法,則是將test命令放置在if..else..fi條件判斷的條件表達(dá)式,然后在其中寫(xiě)上不同的分支邏輯

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

檢測(cè)文件屬性的相關(guān)操作符

如果文件存在,并且具有相應(yīng)的屬性,如下的操作符都會(huì)返回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復(fù)制而來(lái)。

使用上述符號(hào)的方法一模一樣:

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

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可留言交流。

您可能感興趣的文章:
  • PowerShell中使用Test-Path命令檢查文件或文件夾路徑是否存在示例
  • shell判斷文件,目錄是否存在或者具有權(quán)限的代碼
  • 判斷文件是否存在的shell腳本代碼
  • bash判斷文件或文件夾是否存在的shell代碼

標(biāo)簽:六盤(pán)水 滁州 鎮(zhèn)江 丹東 優(yōu)質(zhì)小號(hào) 自貢 百色 武漢

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《使用Bash Shell檢查文件是否存在的方法》,本文關(guān)鍵詞  使用,Bash,Shell,檢查,文件,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《使用Bash Shell檢查文件是否存在的方法》相關(guān)的同類(lèi)信息!
  • 本頁(yè)收集關(guān)于使用Bash Shell檢查文件是否存在的方法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章