【问题标题】:How to check if a file exists before deleting? [duplicate]删除前如何检查文件是否存在? [复制]
【发布时间】:2017-10-19 21:48:55
【问题描述】:

我正在尝试创建一个脚本,如果我的文件存在,则执行删除,然后从 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之间的空格。它应该是file=cageo.crt
  • iamauser 是对的……还要确保您没有使用 rm 的别名。使用完全限定的路径...类似于/bin/rm
  • 您可以将 wget 命令移出 if-then-else-fi 块
  • 这里有一堆使用wget 获取源并用最新的覆盖它们的示例:Noloader | Build-Scripts。脚本不用担心删除旧的旧文件。他们使用wget-O 选项覆盖现有文件。

标签: linux bash shell sh


【解决方案1】:

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

file="cageo.crt"

然后使用,

if [ -f "$file" ]; 

看到这个问题:https://unix.stackexchange.com/questions/258727/spaces-in-variable-assignments-in-shell-scripts

【讨论】:

    猜你喜欢
    • 2011-09-17
    • 2016-02-10
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多