写程式时很多时候需要检查档案或目录是否存在, 在 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 |