脚本需要将一个文件移动到另一个目录;如果没有其父目录树,则无法移动它

脚本需要将一个文件移动到另一个目录;如果没有其父目录树,则无法移动它

在 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

相关内容