移动或复制文件(如果该文件存在)?

move or copy a file if that file exists?

我正在尝试 运行 命令

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

运行正常。但我想提出一个条件,比如如果该文件存在,那么只有 运行 命令。有这样的吗?

我可以放一个 shell 文件。 对于 shell 下面的尝试

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

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

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

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

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

[ -f "/var/www/my_folder/reports.html" ] && mv "/var/www/my_folder/reports.html" /tmp/
  • -f - returns true 文件存在和常规文件时的值

您可以在 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

希望对您有所帮助

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