[英]Unix shell script to check if a file or directory with same name exists
我想檢查是否存在具有相同名稱的文件或目錄。 是否有任何運算符(期望-e
)來檢查文件或目錄,所以我不想添加任何額外條件。
以下代碼可以很好地檢查文件是否存在:
#!/bin/bash
if [ -e /path/to/the/file/sample ]
then
echo "ok"
else
echo "nok"
fi
請注意, sample
可以是文件或目錄。
在我對bash 4.2的測試中,條件[ -e /path/to/the/file/sample ]
對於兩個文件和目錄均適用。
if [ -e /path/to/the/file/sample ] || [ -d /path/to/the/file/sample ];then echo "ok"; else echo "nok";fi
或者使用ls
之類的命令的退出代碼。
if ls "/path/to/the/file/sample" &>/dev/null ; then echo "is here";else echo "not here";fi
如果您嘗試對現有文件或目錄執行ls
,則ls
將返回0,否則將返回非零值(在我的測試中,對於不存在的文件或目錄返回2)。
必須使用引號來處理可能包含空格的正確名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.