![脚本需要将一个文件移动到另一个目录;如果没有其父目录树,则无法移动它](https://linux22.com/image/144710/%E8%84%9A%E6%9C%AC%E9%9C%80%E8%A6%81%E5%B0%86%E4%B8%80%E4%B8%AA%E6%96%87%E4%BB%B6%E7%A7%BB%E5%8A%A8%E5%88%B0%E5%8F%A6%E4%B8%80%E4%B8%AA%E7%9B%AE%E5%BD%95%EF%BC%9B%E5%A6%82%E6%9E%9C%E6%B2%A1%E6%9C%89%E5%85%B6%E7%88%B6%E7%9B%AE%E5%BD%95%E6%A0%91%EF%BC%8C%E5%88%99%E6%97%A0%E6%B3%95%E7%A7%BB%E5%8A%A8%E5%AE%83.png)
在 bash 脚本中,我有:
TEMPPATH="/tmp/directory"
BACKUPPATH="/backup/path"
我正在尝试使用以下方法移动一个文件:
mv $TEMPPATH/file $BACKUPPATH/file
我想将文件从 移动/tmp/directory/file
到/backup/path/file
,但它最终以/backup/path/tmp/directory/file
.我尝试在目标中添加和删除尾部斜杠,并从目标中排除文件名(仅使用目标目录)。我搜索并找到了很多在目录中移动大量文件的方法,但我只想移动一个。
========
编辑:这是导致问题的脚本部分。它是备份 WordPress 文件夹和数据库的脚本的一部分。注意:如果您想知道为什么我不直接将文件压缩到备份位置,那是因为我正在写入 Keybase。如果您还没有使用过 Keybase,因为它的 I/O 速度非常慢,我的目标是在本地压缩文件,然后在压缩完成后移动文件。
#back up the WordPress folder and move over to backup location
echo Compressing site files
zip -r --quiet $TEMPPATH/$DATEFORM-$SITE.wp-content.zip .
echo Moving site zip file to Keybase
#mv $TEMPPATH/$DATEFORM-$SITE.wp-content.zip $BACKUPPATH/$SITE/$DATEFORM-$SITE.wp-content.zip
# ---------> this mv command works as expected:
mv $TEMPPATH/$DATEFORM-$SITE.wp-content.zip $BACKUPPATH/$SITE
#back up the WordPress database, compress, move to backup location and clean up
echo Exporting database
/usr/local/bin/wp db export $TEMPPATH/$DATEFORM-$SITE.sql --all-tablespaces --single-transaction --quick --lock-tables=false --allow-root --skip-themes --skip-plugins
echo Compressing database
zip --quiet $TEMPPATH/$DATEFORM-$SITE.sql.zip $TEMPPATH/$DATEFORM-$SITE.sql
# ---------> this is the way the script was originally written -- maybe this cat method was used to prevent the same problem I am having?
# cat $TEMPPATH/$DATEFORM-$SITE.sql | zip > $TEMPPATH/$DATEFORM-$SITE.sql.zip
echo Moving sql zip file to Keybase
# ---------> this is the mv command that results in the directory tree being copied over to the destination
mv $TEMPPATH/$DATEFORM-$SITE.sql.zip $BACKUPPATH/$SITE
echo Removing tmp file
rm $TEMPPATH/$DATEFORM-$SITE.sql
答案1
我尝试了你的示例,它按预期工作 - 请参阅下面的输出。mv
您使用什么版本以及在什么系统上?还有一条建议,为了避免任何特殊字符(例如带有空格的名称)做意想不到的事情,我建议引用您的变量,并且您可以从目标中删除文件名:mv "$TEMPPATH/file" "$BACKUPPATH/"
。
问题的示例:
$ tree /tmp/directory
/tmp/directory
└── file
0 directories, 1 file
$ tree /backup
/backup
└── path
1 directory, 0 files
$ TEMPPATH="/tmp/directory"
$ BACKUPPATH="/backup/path"
$ mv $TEMPPATH/file $BACKUPPATH/file
$ tree /tmp/directory
/tmp/directory
0 directories, 0 files
$ tree /backup
/backup
└── path
└── file
1 directory, 1 file
仍然无法重现:
$ tree /tmp/test /backup/
/tmp/test
└── some-example.sql
/backup/
└── path
1 directory, 1 file
$ TEMPPATH=/tmp/test
$ DATEFORM=some
$ SITE=example
$ BACKUPPATH=/backup/path
$ zip --quiet $TEMPPATH/$DATEFORM-$SITE.sql.zip $TEMPPATH/$DATEFORM-$SITE.sql
$ mv $TEMPPATH/$DATEFORM-$SITE.sql.zip $BACKUPPATH/$SITE
$ tree /tmp/test /backup/
/tmp/test
└── some-example.sql
/backup/
└── path
└── example
1 directory, 2 files