The Code Cave

January 18, 2007

What is wrong with this bash script?

Filed under: Bash — Brian @ 3:57 pm

It should say that test.zip is a zip file, but the if statments, which check for TAR in the file name, all return true… If I do this outside of an if statement, say at the shell prompt, it works correctly.

What is wrong with this statement:

DOS:
  1. #$bash
  2.  
  3. ArchiveName="test.zip"
  4. cur_file="test.zip"
  5. echo "ArchiveName: $ArchiveName"
  6.  
  7. if [ $(echo $ArchiveName | grep "tar$" -i)=$ArchiveName ]
  8. then
  9.   echo Test1: It is a tar file
  10. else
  11.   echo Test1: It is a zip file
  12. fi
  13.  
  14. if [ $(echo $ArchiveName | grep "tar.gz$" -i)=$ArchiveName ]
  15. then
  16.   echo Test2: It is a tar file
  17. else
  18.   echo Test2: It is a zip file
  19. fi
  20.  
  21. if [ $(echo $ArchiveName | grep "tar$" -i)=$ArchiveName ] || [ $(echo "$ArchiveName" | grep "tar.gz$" -i)=$ArchiveName ]
  22. then
  23.   echo Test3: It is a tar file
  24. else
  25.   echo Test3: It is a zip file
  26. fi

Is there a better way to do this?

3 Comments »

  1. if [ $(echo $ArchiveName | grep -i "tar$" ) ]
    then
    echo Test1: It is a tar file
    else
    echo Test1: It is a zip file
    fi

    that works for me. (i'm using unix, so put your -i back where it belongs)

    Comment by digitalramble — January 19, 2007 @ 3:15 pm

  2. Cripes.

    DOS:
    1. if [ $(echo $ArchiveName | grep -i "tar$" ) ]
    2. then
    3.   echo Test1: It is a tar file
    4. else
    5.   echo Test1: It is a zip file
    6. fi

    You need a preview plugin :-)

    Comment by digitalramble — January 19, 2007 @ 3:16 pm

  3. Thanks Cindy!

    That works Great!

    DOS:
    1. #$bash
    2.  
    3. ArchiveName="test.tar"
    4. #ArchiveName="test.zip"
    5. #ArchiveName="test.tar.gz"
    6. echo "ArchiveName: $ArchiveName"
    7.  
    8. if [ $(echo $ArchiveName | grep -i "tar$" ) ]
    9. then
    10.   echo Test1: It is a tar file
    11. else
    12.   echo Test1: It is not a tar file
    13. fi
    14.  
    15. if [ $(echo $ArchiveName | grep -i "tar.gz$" ) ]
    16. then
    17.   echo Test2: It is a tar.gz file
    18. else
    19.   echo Test2: It is not a tar.gz file
    20. fi
    21.  
    22. if [ $(echo $ArchiveName | grep -i "tar$" ) ] || [ $(echo $ArchiveName | grep -i "tar.gz$" ) ]
    23. then
    24.   echo Test3: It is a tar file
    25. else
    26.   echo Test3: It is a zip file
    27. fi

    Comment by Brian — January 19, 2007 @ 3:41 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress