提取 zip 文件,然后使用不同的文件名将其 cd 进去

Extracting zip file and then cd into it with different filename

我正在创建一个 bash 脚本来提取一个 tar 文件并 cd 进入它,然后它运行另一个脚本。到目前为止,这在我下面的代码中运行得很好,但是,我 运行 遇到这样一种情况,如果提取的文件夹与 .tar 文件名不同,则会导致问题。所以我的问题是,我应该如何处理文件名不同于 .tar filename.

的特殊情况

e.g,) my_file.tar ---> 提取后 ----> my_different_file_name

#!/bin/bash

fname=

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

也许你可以这样做:

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

你可以做一个:

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

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

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

# 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