如何在删除前检查文件是否存在?
问题描述:
我想创建一个脚本,如果我的文件存在然后执行删除,然后从artifactory得到wget
。下面这段代码运行出于某种原因不会删除我的文件,并创建一个新的扩展名...例如cageo.crt.1
,.2
,.3
等如何在删除前检查文件是否存在?
当我尝试调试它会显示rm -f
但没有文件名
#!/bin/bash -ex
#install Certificate
cd /deployment/scripts
# check if cert is already installed
file = cageo.crt
if [ -f $file ]; then
echo "File $file exists."
echo "Delete file and get latest"
rm -f $file
wget https://artifactory.geo.com/artifactory/cageo.crt
else
wget https://artifactory.geo.com/artifactory/cageo.crt
fi
这是我的输出:
+ cd /deployment/scripts
+ file = cageo.crt
=: cannot open (No such file or directory)
cageo.crt: PEM certificate
+ '[' -f ']'
+ echo 'File exists.'
File exists.
+ echo 'Delete file and get latest'
Delete file and get latest
+ rm -f
+ wgethttps://artifactory.geo.com/artifactory/cageo.crt/cageo.crt
--2017-10-19 17:39:16-- https://artifactory.geo.com/artifactory/cageo.crt/cageo.crt
Resolving artifactory.geo.com (artifactory.geo.com)... 10.0.138.51
Connecting to artifactory.geo.com (artifactory.geo.com)|10.0.138.51|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1675 (1.6K) [application/octet-stream]
Saving to: ‘cageo.crt.4’
答
壳分配变量时,取出的空间。它应该阅读,
file="cageo.crt"
然后用,
if [ -f "$file" ];
见这太问题:https://unix.stackexchange.com/questions/258727/spaces-in-variable-assignments-in-shell-scripts
删除'file','='和'cageo.crt'之间的空间。它应该读取'file = cageo.crt' – iamauser
iamauser是正确的...还要确保你没有使用rm的别名。使用完全合格的路径...就像'/ bin/rm'。 –
您可以将wget命令移出if-then-else-fi块 –