jaros
jaros

Reputation: 333

Unpack .tar.gz and modify result files

I wanted to write a bash script that will unpack .tar.gz archives and for each result file it will set an additional attribute with the name of the original archive. Just to know what the origin is of the unpacked file.

I tried to store the inside files in an array and then for-loop them.

for archive in "$1"*.tar.gz; do
    if [ -f "${archive}" ]
        then
            readarray -t fileNames < <(tar tzf "$archive")
            for file in "${fileNames}"; do
                echo "${file}"
                tar xvzf "${archive}" -C "$1" --no-wildcards "${file}" &&
                attr -s package -V "${archive}" "${file}"
            done
    fi
done

The result is that only one file is extracted and no extra attribute is set.

Upvotes: 0

Views: 219

Answers (1)

dash-o
dash-o

Reputation: 14452

#! /bin/bash

for archive in "$1"*.tar.gz; do
    if [ -f "${archive}" ] ; then
        # Unpack the archive into subfolder $1
        tar xvf "$archive" -C "$1"
        # Assign attributes
        tar tf "$archive" | (cd "$1" && xargs -t -L1 attr -s package -V "$archive" )
    fi
done

Notes:

  1. Script is unpacking each archive with a single 'tar'. This is more efficient than unpacing one file at a time. It also avoid issues with unpacking folders, which will lead to unnecessary repeated work.
  2. Script is using 'attr'. Will be better to use 'setfattr', if supported on target file system to set attributes on multiple files with a few calls (using xargs, with multiple files per command)
  3. It is not clear what is the structure of the output folder. From the question, it looks as if all archives will be placed into the same folder "$1". The following solution assume that this is the intended behavior, and that each archive will have distinct file names. If each archive is to be placed into different sub folder, it will be easier/more efficient to implement.

Upvotes: 1

Related Questions