【问题标题】:Extracting zip file and then cd into it with different filename提取 zip 文件,然后用不同的文件名 cd 进入它
【发布时间】:2016-05-02 06:05:46
【问题描述】:

我正在创建一个 bash 脚本来提取一个 tar 文件并将其放入其中,然后它会运行另一个脚本。到目前为止,这在我下面的代码中运行良好,但是,我遇到了一个情况,如果提取的文件夹与 .tar 文件名不同,那么它会导致问题。所以我的问题是,我应该如何处理文件名不同于 .tar 文件名的特殊情况。

例如)my_file.tar ---> 提取后 ----> my_different_file_name

#!/bin/bash

fname=$1

echo the file you are about to extract is $fname

if [ -f $fname ]; then         #if the file exists
    tar -xvzf $fname       #tar it
    cd ${fname%.*}         #the `%.*` will extract filename from     filename.tgz and cd into it
    echo ${fname%.*}
    echo $PWD
    loadIt                 #another script to load
fi

【问题讨论】:

  • 您的压缩包是否只会创建 one 顶级目录?如果是这样,并且您的起始目录是干净的,那么 cd * 将起作用(但如果不是这种情况,则不可靠)。是否有可用于查找目标目录的解压缩 tarball 的内容?
  • @EtanReisner 不,可能还有其他目录已经存在于同一级别,如果我这样做cd *,我相信它会 cd 进入与刚刚提取的目录不同的目录。跨度>

标签: linux bash tar


【解决方案1】:

你可以这样做:

 topDir=$(tar -xvzf $fname | sed "s|/.*$||" | uniq)
 [ $(wc -w <<< $topDir) == 1 ] || exit 1
 echo topDir=$topDir

解释:第一个命令解压很麻烦(输出它解压的所有文件),然后获取所有前导目录名称,并将它们通过管道传输到 uniq。 (所以基本上它会返回 tar 文件中所有顶级目录的列表)。下一行检查 topDir 中是否有一个条目,否则退出。 此时 $topdir 将是您要 cd 进入的目录。

【讨论】:

  • 当我尝试它在第二行给我[ 0 == 1 ]
  • @kkmoslehpour 您是否将-v 与tar 一起使用? 0 表示 wc 输出意味着没有任何内容。
  • @John 是的,我尝试了上面的确切代码,但给了我 0 表示 wc
  • 这可能是几件事:1) tar 文件实际上是空的(尝试运行tar -tf tarfile.tar.gz 来确认,2)$fname 没有正确填充(它是空的或指向一个不存在的 tar 文件,或者它指向一个不是用 gzip 创建的 tar 文件)。这将导致 tar 向 stderr 吐出一条消息。 3) tar 文件只包含文件(没有子目录)。你可以尝试在命令行手动运行tar -xvzf tarfile.tar.gz,看看你得到了什么。
  • @John 这行得通,但是,你能解释一下你在那里执行的 sed 命令吗?我不太明白它在那里做了什么。此外,这仅适用于 tgz 文件,如果文件是 .zip,这将不起作用,有没有办法对 zip 文件做同样的事情?
【解决方案2】:

也许你可以这样做:

cd $(tar -tf $fname | head -1)

【讨论】:

  • 不能保证第一个条目是顶级目录——一些 tar 文件根本不存储目录名。
  • 确认。我假设每个 tar 文件都只有一个顶级文件夹。但是如果在这种特定情况下不能保证这一点,也许最好使用“find”来确保“loadIt”存在并找到它的正确位置。
  • @Fredi 嗨,这个解决方案实际上可以工作,但是,假设它不是 tar,而是 zip 或任何其他压缩文件,有没有办法处理这个问题?
  • 同样,这不起作用,因为 tar 不保证顶级目录将是 tar 文件中的第一个条目。根据 tar 文件的创建方式(使用的 tar 版本、运行次数等),您可能会得到不同的结果。假设这会使您的代码容易出错。如果您想假设文件夹中的所有内容都在一个目录中,那么您可以使用 sed 删除 tar 文件第一个条目中第一个 / 之后的所有内容。这样会更安全。
【解决方案3】:

如果你不介意在解压后移动目录,你可以这样做

# Create a temporary directory
$ tmpd=$(mktemp -d)
# Change to the temporary directory
$ pushd "$tmpd"
# Extract the tarball
$ tar -xf "$fname"
# Glob the directory name
$ d=(*)
# Error if we have more (or less) than one directory
$ [ "${#d}" = 0 ] || exit 1
# Explicitly use just the first directory (optional since `$d` does the same thing)
$ d=${d[0]}
# Move the extracted directory to the previous directory
$ mv "$d" "$OLDPWD"
# Change back to the starting directory
$ popd
# Remove the (now empty) temporary directory
$ rmdir "$tmpd"
# Change into the extracted directory
$ cd "$d"
# Run 'loadIt'
$ loadIt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多