我正在编写一个备份脚本,想要打包一个文件目录:
tar czf ~/backup.tgz /home/username/drupal/sites/default/files
这会将它打成tar包,但是当我解压缩得到的文件时,它包含了完整的文件结构:文件在home/username/drupal/sites/default/files
中。
有没有一种方法可以排除父目录,这样生成的tar只知道最后一个目录(files
)?
使用 --directory 选项:
tar czf ~/backup.tgz --directory=/home/username/drupal/sites/default files
嗨,当进入指定目录时(例如Makefile等),我有一个更好的解决方案。
tar -cjvf files.tar.bz2 -C directory/contents/to/be/compressed .
请勿忘记在末尾加上句点(.)!!.
"的文件夹。 - derpedy-doocd /home/username/drupal/sites/default/files
tar czf ~/backup.tgz *
tar czf $sourcedir/$backup_dir.tar --directory=$sourcedir WEB-INF en
tar -xvf $deploydir/med365/$backup_dir.tar -C $deploydir/med365/
scp -r -i $privatekey $sourcedir/$backup_dir.tar $server:$deploydir/med365/
echo "File uploaded.. deployment folders"
ssh -i $privatekey $server tar -xvf $deploydir/med365/$backup_dir.tar -C $deploydir/med365/
基于 nbt 和 MaikoID 的解决方案,我们可以进一步改进:
tar -czf destination.tar.gz -C source/directory $(ls source/directory)
.
)然而,它需要两次给出目录,因此在另一个脚本中可能更有用。如果在source/directory
中有大量文件/文件夹,则效率可能较低。根据需要调整子命令。
例如对于以下结构:
|- source
| |- one
| `- two
`- working
working$ tar -czf destination.tar.gz -C ../source $(ls ../source)
执行该命令将会生成一个名为destination.tar.gz
的文件,其中包含了one
和two
(以及它们的子文件和子文件夹)作为第一级目录。
要将/home/myuser/workspace/zip_from/
中的所有txt(*.txt)文件解压缩到/home/myuser/workspace/zip_to/
,并且不保留源文件的目录结构,请使用以下命令:
tar -P -cvzf /home/myuser/workspace/zip_to/mydoc.tar.gz --directory="/home/myuser/workspace/zip_from/" *.txt
tar -xzv --strip-components=5 -f backup.tgz
我在https://www.baeldung.com/linux/tar-archive-without-directory-structure#5-using-the---strip-components-option上找到了这个技巧。对我来说,-C或--directory都不起作用,我使用这个
cd source/directory/or/file
tar -cvzf destination/packaged-app.tgz *.jar
# this will put your current directory to what it previously was
cd -
gzip -dc "<your_file>.tgz" | tar x -C <location>
tar -C <directoryPath> -cvzf <Path of the tar.gz file> filename1 filename2... filename N
例如:
tar -C /home/project/files -cvzf /home/project/files/test.tar.gz text1.txt text2.txt
--directory="/home/username/drupal/sites/default files"
放在目标~/backup.tgz
的前面。 - Chris Stryczynski--directory
选项所给出的路径不是"/home/username/drupal/sites/default files"
。它是/home/username/drupal/sites/default
,后面跟着一个位置参数,指定要打包成 tar 包的目录名称为files
。 - Chap