Luke_Nuke
Luke_Nuke

Reputation: 471

How to check if file is tar file in Bash shell?

My question is about Bash, Shell. I am writing a script and I have the following problem: I have a case when user declares that he or she will extract a file into a dir. But I have to test if the existence and if exist a need to check if that file is a *.tar file. I searched for similar like when checking if the file is executable:

if [ -x "file" ]; then
 echo "file is executable"
else
 echo "file is not executable"

# will this if test work?
case $1
"--extract")
 if [ -e $2 ] && [ tar -tzf $2 >/dev/null ]; then
  echo "file exists and is tar archive"
 else
  echo "file either does not exists or it is not .tar arcive"
 fi
;;
esac

Code from above doesn't work it is totally ignored. Any ideas?

Upvotes: 2

Views: 15859

Answers (4)

slm
slm

Reputation: 16416

I usually use a construct like this based off of the file command.

gzipped tarballs
$ file somefile1.tar.gz | grep -q 'gzip compressed data' && echo yes || echo no
yes

$ file somefile2.tar.gz | grep -q 'gzip compressed data' && echo yes || echo no
no
tarballs

The above handles gzipped tarball files, for uncompressed change out the string that grep detects:

$ file somefile1.tar | grep -q 'POSIX tar archive' && echo yes || echo no
yes

$ file somefile2.tar | grep -q 'POSIX tar archive' && echo yes || echo no
no

Upvotes: 1

Luke_Nuke
Luke_Nuke

Reputation: 471

OK, I found the answer. I know that this is not most optimal, however, it works as I intended.

I put case $1 from user into a variable and create another variable equal to *.tar.gz then in if statement I compare var1 (string from user input) with var2 equal to *tar.gz and it works.

Upvotes: 0

Gonzalo Matheu
Gonzalo Matheu

Reputation: 10064

file command can determine file type:

file my.tar

if it is a tar file it will output:

my.tar: POSIX tar archive (GNU)

Then you can use grep to check the output (whether or not contains tar archive):

file my.tar | grep -q 'tar archive; && echo "I'm tar" || echo "I'm not tar"

In case the file does not exis, file output will be (with exit code 0):

do-not-exist.txt: cannot open `do-not-exist.txt' (No such file or directory).

You could use a case statement to handle several types of files.

Upvotes: 4

glenn jackman
glenn jackman

Reputation: 246827

I would just see if tar can list the file:

if ! { tar ztf "$file" || tar tf "$file"; } >/dev/null 2>&1; then
    echo "$file is not a tar file"
fi

Upvotes: 2

Related Questions