目錄
一、檔案測驗運算子
二、常用實體
2.1 -d file 檢測目錄
2.2 -f file 檢測普通檔案
2.3 -x file 檢測檔案可執行
2.4 -e file 檢測檔案/目錄存在
2.5 -b file 檢測塊設備檔案
三、總結
在 Shell 編程中,檔案測驗運算子使用的很廣泛,經常需要檢測一個檔案的屬性,下面結合實體進行說明,
一、檔案測驗運算子
| 運算子 | 說明 |
|---|---|
| -b file | 檢測檔案是否是塊設備檔案,如果是,則回傳 true, |
| -c file | 檢測檔案是否是字符設備檔案,如果是,則回傳 true, |
| -d file | 檢測檔案是否是目錄,如果是,則回傳 true, |
| -f file | 檢測檔案是否是普通檔案(既不是目錄,也不是設備檔案),如果是,則回傳 true, |
| -g file | 檢測檔案是否設定了 SGID 位,如果是,則回傳 true, |
| -u file | 檢測檔案是否設定了 SUID 位,如果是,則回傳 true, |
| -k file | 檢測檔案是否設定了粘著位(Sticky Bit),如果是,則回傳 true, |
| -p file | 檢測檔案是否是有名管道,如果是,則回傳 true, |
| -r file | 檢測檔案是否可讀,如果是,則回傳 true, |
| -w file | 檢測檔案是否可寫,如果是,則回傳 true, |
| -x file | 檢測檔案是否可執行,如果是,則回傳 true, |
| -s file | 檢測檔案是否為空(檔案大小是否大于0),不為慷訓傳 true, |
| -e file | 檢測檔案(包括目錄)是否存在,如果是,則回傳 true, |
二、常用實體
2.1 -d file 檢測目錄
#!/bin/bash
file="/root"
if [ -d $file ]
then
echo "$file is directory!"
else
echo "$file is not directory!"
fi
輸出:
[root@localhost Shell]# ./dir.sh
/root is directory!
[root@localhost Shell]#
2.2 -f file 檢測普通檔案
#!/bin/bash
file="/root/regularFile"
if [ -f $file ]
then
echo "$file is regular file!"
else
echo "$file is not regular file!"
fi
輸出:
[root@localhost Shell]# ./dir.sh
/root/regularFile is regular file!
[root@localhost Shell]#
2.3 -x file 檢測檔案可執行
#!/bin/bash
file="/root/Shell/dir.sh"
if [ -x $file ]
then
echo "$file is executable file!"
else
echo "$file is not executable file!"
fi
輸出:
[root@localhost Shell]# ls -l dir.sh
-rwxr-xr-x. 1 root root 145 2月 6 10:54 dir.sh
[root@localhost Shell]# ./dir.sh
/root/Shell/dir.sh is executable file!
[root@localhost Shell]#
2.4 -e file 檢測檔案/目錄存在
#!/bin/bash
file="/root"
if [ -e $file ]
then
echo "$file is exist!"
else
echo "$file is not exist!"
fi
輸出:
[root@localhost Shell]# ./dir.sh
/root is exist!
[root@localhost Shell]#
2.5 -b file 檢測塊設備檔案
#!/bin/bash
if [ -b /dev/sda ]
then
echo "/dev/sda is Block Device File!"
else
echo "/dev/sda is not Block Device File!"
fi
輸出為:
[root@localhost Shell]# ./dir.sh
/dev/sda is Block Device File!
[root@localhost Shell]#
三、總結
檔案測驗運算子在 Shell 編程中經常使用,幾個常用的運算子要記住,
參考文獻:
[1] https://www.cnblogs.com/GyForever1004/p/8457028.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/257375.html
標籤:其他
上一篇:VirtualBox虛擬機環境下配置Ubuntu系統,安裝Anaconda
下一篇:基本的Dos命令(慢慢更新~)
