Actually the string is new.tar.gz I want to check this file is tar package or not ?


Use the file command to inspect it.

$ file new.tar.gz
new.tar.gz: gzip compressed data, last modified: Tue Sep 26 16:50:00 2017, from Unix

To inspect the contents of the compressed file, you'll have to extract it, then run file on that:

$ gunzip -k new.tar.gz; file new.tar
new.tar: POSIX tar archive (GNU)

Technically, a tar archive file may be called anything. The name of a file does not decide the format or contents of the file in Unix.

However, if we restrict the question to determining whether a filename in the variable $filename ether ends with the string .tar or contains the string .tar., or not:

case $filename in
    *.tar|*.tar.*) echo 'possibly a tar file' ;;

The above allows for both .tar at the end of a name or .tar followed by another extension.

Or, in bash (the above works in any sh shell, including bash):

if [[ $filename =~ \.tar$  ]] ||
   [[ $filename =~ \.tar\. ]]; then
    echo 'possibly a tar file'


if [[ $filename == *.tar   ]] ||
   [[ $filename == *.tar.* ]]; then
    echo 'possibly a tar file'

If you have a file with a long list of filenames, then the following will tell you which lines in that file ends with the string .tar or contains the string .tar.:

grep -E '\.tar$|\.tar\.' file.list

The -E flag tells grep to treat the given pattern as an extended regular expression (to handle |).


grep -e '\.tar$' -e '\.tar\.' file.list

To list the final extensions of every file in a long list (stored in file.list):

sed 's/.*\.//' file.list

The sed expression s/.*\.// will remove everything on each line up to and including the final dot.

  • 1
    You can also use pattern matching in bash, which is often a little cleaner than the corresponding regular expression. if [[ $filename = *.tar ]] || [[ $filename = *.tar.* ]]. (With extended pattern support enabled, [[ $filename = *.tar?(.*) ]].
    – chepner
    Sep 26 '17 at 17:46
  • @chepner Thanks. Personally, I prefer case ... esac for pattern mating. More portable. Added some of your stuff.
    – Kusalananda
    Sep 26 '17 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.