With your question tagged shell
unix
sh
, your question requests an answer that is POSIX shell compliant, but your response within the comments indicates you are working in bash (or some other shell that supports arrays). Depending upon your shell, tagging makes a difference in the answers you will receive and what will (or won't) work for you. (as @Inian correctly points out)
If you are working in a shell that supports arrays (bash, ksh, zsh, etc), the easiest way to capture the output of the tar -xvf testfile.txt
command is by using command substitution to fill an array, e.g.
array=( $(tar -tvf testfile.tar) )
In the event you need a POSIX shell solution (Bourne shell, dash, etc) then you will either need to pipe the output from tar
to read
or redirect its output to a temporary file and read
the output from there. You can use something similar to the following,
tar -tvf testfile.tar | while IFS="\n" read -r fname
do
printf "found: %s\n" "$fname"
done
Or if you would like to use a temporary file, then something like the following:
tar -tvf testfile.tar > tempfile.txt
while IFS="\n" read -r fname
do
printf "found: %s\n" "$fname"
done <"tempfile.txt"
rm tempfile.txt
note: depending on your OS and implementation of read
, you may or may not have the -r
option available. Simply omit if your implementation does not provide it.
Glad you were able to get this sorted out. If you have any further questions, please let us know.