【问题标题】:move or copy a file if that file exists?如果该文件存在,则移动或复制该文件?
【发布时间】:2018-04-19 15:24:36
【问题描述】:

我正在尝试运行命令

mv /var/www/my_folder/reports.html /tmp/

它运行正常。但我想设置一个条件,比如该文件是否存在,然后只运行命令。有这样的吗?

我可以放一个 shell 文件。 换壳试试下面的东西

if [ -e /var/www/my_folder/reports.html ]
  then
  mv /var/www/my_folder/reports.html /tmp/
fi

但我需要一个命令。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 为什么需要命令?

标签: linux centos mv


【解决方案1】:

也许您的用例是“如果不存在则创建,然后始终复制”。 然后:touch myfile && cp myfile mydest/

【讨论】:

    【解决方案2】:

    如果存在文件,然后通过标准错误输出移动或回显消息

    test -e /var/www/my_folder/reports.html && mv /var/www/my_folder/reports.html /tmp/ || echo "not existing the file" >&2
    

    【讨论】:

    • 它也在扔同样的东西。
    • 我回答你的问题比@RomanPerekhrest 晚了一些。你可以看到我的回答时间:|
    【解决方案3】:

    你可以简单地在 shell 脚本中完成它

    #!/bin/bash
    
    # Check for the file
    ls /var/www/my_folder/ | grep reports.html > /dev/null
    
    # check output of the previous command
    if [ $? -eq 0 ]
    then
        # echo -e "Found file"
        mv /var/www/my_folder/reports.html /tmp/
    else
        # echo -e "File is not in there"
    fi
    

    希望对你有帮助

    【讨论】:

      【解决方案4】:

      仅当文件/var/www/my_folder/reports.html 存在且常规文件时才移动它:

      [ -f "/var/www/my_folder/reports.html" ] && mv "/var/www/my_folder/reports.html" /tmp/
      
      • -f - 如果文件存在且常规文件,则返回 true

      【讨论】:

      • 如果文件没有怎么办?它会抛出错误并将状态代码从 0 更改为 1 还是返回 false(这并不意味着命令因错误而中断)?
      猜你喜欢
      • 1970-01-01
      • 2021-01-14
      • 2014-01-04
      • 2017-01-07
      • 2015-10-31
      • 2013-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多