寫程式時很多時候需要檢查檔案或目錄是否存在, 在 Shell Script 檢查檔案及目錄是否存在, 可以在 if 條件判斷式裡面加上 -e 或 -d 實現, 以下是具體寫法:
檢查檔案是否存在:
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 |
上面的 if 判斷式也可以用一行來實現:
1 2 3 |
#!/bin/sh [ -f /path/to/dir/filename ] && echo "File exists" || echo "File not exists" |
檢查目錄是否存在:
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 |
#!/bin/sh [ -d /path/to/dir ] && echo "Directory exists" || echo "Directory not exists" |
其中一個十分實用的例子, 是檢查檔案或目錄是否存在, 如果不存在就便宜檔案或目錄:
This is the best practice to check file existence before creating them else you will get an error message. This is very helpful while creating shell scripts required file or directory creation during runtime.
如果檔案不存在, 便用 touch 建立檔案:
1 2 |
#!/bin/sh [ ! -f /tmp/testfile.log ] && touch /tmp/testfile.log |
如果目錄不存在, 便用 mkdir 建立檔案:
1 2 |
#!/bin/sh [ ! -d /tmp/mydir ] && mkdir -p /tmp/mydir |