Skip to content
Advertisement

How can I read the files from a tar command into an array using BASH?

Using a BASH script, how can I execute a tar command and read the output (the list of files) into an array?

I’ve tried a number of things, including:

fileNames=`tar xvfz ${compressedFile} | readarray`

tar xvfz ${compressedFile} | readarray fileNames

readarray fileNames < tar xvfz ${compressedFile}

files=`tar xvfz ${compressedFile}'
readarray fileNames < ${files}

readarray fileNames < `echo ${files}`

I’ve tried with and without the backquote (grave accent) and I’ve tried using t as an option on the tar.gz file. I was trying to accomplish this without sending the output to a file and then reading the file, but I guess that’s my fall-back plan (though I haven’t tried it yet).

The closest I’ve come is:

echo ${fileNames} | readarray fileNames

but this creates only 1 item in the array and it contains all of the file names. Argh. 🙂

Anyone know how to accomplish this (seemingly) easy task?

V

Advertisement

Answer

This should create array with contents of tar file:

IFS=$'n' declare -a fileNames=($(tar tzf "$compressedFile"))

This is assuming your file names inside tar file don’t have newlines.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement