Shell Script 检查档案或目录是否存在


写程式时很多时候需要检查档案或目录是否存在, 在 Shell Script 检查档案及目录是否存在, 可以在 if 条件判断式里面加上 -e 或 -d 实现, 以下是具体写法:

检查档案是否存在:

上面的 if 判断式也可以用一行来实现:

检查目录是否存在:

用一行来实现上面的程式码:

其中一个十分实用的例子, 是检查档案或目录是否存在, 如果不存在就便宜档案或目录:
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 建立档案:

如果目录不存在, 便用 mkdir 建立档案:

Leave a Reply