简体   繁体   English

Bash Shell脚本提取存档

[英]Bash shell script to extract archive

I am trying to convert the following script which I use to create archives into one which extracts them. 我正在尝试将以下用于创建档案的脚本转换为将其解压缩的脚本。

[[ $# -lt 2 ]] && exit 1

name=$1; shift
files=("$@")

#exclude all files/directories that are not readable
for index in "${!files[@]}"; do
   [[ -r ${files[index]} ]] || unset "files[index]"
done

[[ ${#files[@]} -eq 0 ]] && exit 1    

if tar -czvf "${name:-def_$$}.tar.gz" "${files[@]}"; then
   echo "Ok"
else
   echo "Error"
   exit 1
fi

So far I have this: 到目前为止,我有这个:

[[ $# -lt 1 ]] && exit 1

files=("$@")

#remove files and directories which are not readable
for index in "${!files[@]}"; do
        [[ -r ${files[index]} ]] || unset "files[index]"
done

[[ ${#files[@]} -eq 0 ]] && exit 1

if tar -xzvf "${files[@]}".tar.gz; then
        echo "OK"
else
        echo "Error"
        exit 1
fi

I dont know whether I needed to keep the shift as for this script I do not need to discard any arguments. 我不知道是否需要保持班次不变,因为我不需要放弃任何参数。 I want to be able to take them all and unzip each one. 我希望能够将它们全部拿走并解压。 Also I see there is a -C switch which allows the user to choose where the unzipped files go. 我还看到有一个-C开关,它允许用户选择解压缩文件的位置。 How would I go about also adding this as an option for the user because they may or may not want to change the directory where the files get unzipped to. 我还将如何将此添加为用户选项,因为他们可能会或可能不想更改文件解压缩到的目录。

You unfortunately can't just do tar -xzvf one.tar.gz two.tar.gz . 不幸的是,您不能只执行tar -xzvf one.tar.gz two.tar.gz Straightforward approach is to use a good old for loop: 简单的方法是使用一个很好的for循环:

for file in "${files[@]}"; do
   tar -xzvf "$file"
done

Or you can use this: 或者您可以使用以下命令:

cat "${files[@]}" | tar -xzvf - -i

You can have the first argument to be the specified directory for the -C option: 您可以使第一个参数成为-C选项的指定目录:

[[ $# -lt 2 ]] && exit 1

target=$1; shift
files=("$@")

#remove files and directories which are not readable
for index in "${!files[@]}"; do
   [[ -r ${files[index]} ]] || unset "files[index]"
done

[[ ${#files[@]} -eq 0 ]] && exit 1

mkdir -p -- "$target" || exit 1

for file in "${files[@]}"; do
   tar -xzvf "$file" -C "$target"
done
./script /some/path one.tar.gz two.tar.gz

List of files for tar can be also constructed like this: tar的文件列表也可以这样构造:

target=$1; shift

for file; do
   [[ -r $file ]] && files+=("$file")
done 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM