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

move only if file exists in a shell script

我想用mv重命名一个文件:

mv src.txt dest.txt

如果文件不存在,我得到一个错误:

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

如何仅在文件已存在的情况下使用 mv

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

你应该测试文件是否存在

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

一行:

[ -f old ] && mv old nu

这一行returns成功即使找不到文件:

[ ! -f src ] || mv src dest