仅当文件存在于shell脚本中时才移动

时间:2022-01-25 23:50:19

As part of a backup script I want to call mv on a file to rename it:

作为备份脚本的一部分,我想在文件上调用mv来重命名它:

mv example.txt example2.txt

If the file doesn't exist, I am receiving the error:

如果该文件不存在,我收到错误:

mv: cannot stat ‘example.txt’: No such file or directory

How do I call the mv only if the file already exists?

仅当文件已存在时,如何调用mv?

I don't really want to redirect stderr to dev/null as I'd quite like to keep any other errors that occur.

我真的不想将stderr重定向到dev / null,因为我很想保留任何其他错误。

2 个解决方案

#1


16  

You should test if the file exists

您应该测试该文件是否存在

if [ -f blah ]; then
   mv blah destination
fi

#2


9  

One-liner:

一内胆:

[ -f old ] && mv old nu

#1


16  

You should test if the file exists

您应该测试该文件是否存在

if [ -f blah ]; then
   mv blah destination
fi

#2


9  

One-liner:

一内胆:

[ -f old ] && mv old nu