如何在删除之前检查文件是否存在?

时间:2017-10-19 21:48:56

标签: linux bash shell sh

我试图创建一个脚本,如果我存在文件然后执行删除然后从神器中获取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’

1 个答案:

答案 0 :(得分:2)

在shell中分配变量时删除空格。它应该读,

file="cageo.crt"

然后使用,

if [ -f "$file" ]; 

请参阅此问题:https://unix.stackexchange.com/questions/258727/spaces-in-variable-assignments-in-shell-scripts