我的解决方案推荐的背景是一个朋友的故事,他在第二周
他的第一份工作,擦掉了一半的构建服务器。所以基本任务是确定文件是否存在,
如果是这样,让我们删除它。但这条河上有几处险峻的急流:
考虑以下场景:
我们有要删除的文件:filesexists.json
这个文件名存储在一个变量中
<host>:~/Documents/thisfolderexists filevariable="filesexists.json"
我们也有一个路径变量来让事情变得非常灵活
<host>:~/Documents/thisfolderexists pathtofile=".."
<host>:~/Documents/thisfolderexists ls $pathtofile
filesexists.json history20170728 SE-Data-API.pem thisfolderexists
那么让我们看看-e 是否做了它应该做的事情。文件是否存在?
<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?
0
确实如此。魔法。
但是,如果文件变量不小心被评估为 nuffin',会发生什么
<host>:~/Documents/thisfolderexists filevariable=""
<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?
0
什么?它应该返回一个错误......这就是故事的开始
文件夹不小心被删除了
另一种方法是专门测试我们理解为“文件”的内容
<host>:~/Documents/thisfolderexists filevariable="filesexists.json"
<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?
0
所以文件存在...
<host>:~/Documents/thisfolderexists filevariable=""
<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?
1
所以这不是一个文件,也许我们不想删除整个目录
man test 有话要说:
-b FILE
FILE exists and is block special
-c FILE
FILE exists and is character special
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
...
-h FILE
FILE exists and is a symbolic link (same as -L)