在 Shell Script 檢查檔案及目錄是否存跟 Perl 很相似, 都是透過 -e 及 -d 在 if 裡面判斷, 寫法如下:
檢查目錄是否存在
|
1 2 3 4 5 6 7 8 9 |
#!/bin/sh if [ -d "/path/to/dir" ]; then # 目錄 /path/to/dir 存在 echo "Directory /path/to/dir exists." else # 目錄 /path/to/dir 不存在 echo "Directory /path/to/dir does not exists." fi |
檢查檔案是否存在
|
1 2 3 4 5 6 7 8 9 |
#!/bin/sh if [ -f "/path/to/dir/filename" ]; then # 檔案 /path/to/dir/filename 存在 echo "File /path/to/dir/filename exists." else # 檔案 /path/to/dir/filename 不存在 echo "File /path/to/dir/filename does not exists." fi |
判斷檔案是否存在,應該是”-f”而不是”-d”喔~^__^
謝謝指正, 已修正.