Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

This is driving me insane. There are many posts on this but nothing is working for me. I want to check if a file is not an avi or mpg then I want to exit. Here is a simple example:

#!/bin/sh

extension="avi"
if [ $extension != "avi" ] || [ $extension != "mpg" ]; then
        echo "ERROR: File is not an avi or mpg"
        exit 1
fi
echo "I should print out"

This always returns the ERROR message which it shouldn't. I've also tried:

if [[ $extension != "avi" ]] || [[ $extension != "mpg" ]]; then
if ([[ $extension != "avi" ]] || [[ $extension != "mpg" ]]); then
if [ $extension != "avi" -o $extension != "mpg" ]; then

What am I missing?

share|improve this question
add comment

2 Answers 2

up vote 3 down vote accepted

You made a mistake in your logic. Both conditions have to be filled not just one so you need the AND (&&) operator instead of the OR (||). Try:

if [ $extension != "avi" ] && [ $extension != "mpg" ]; then

or more elegant:

if [ $extension != "avi" -a $extension != "mpg" ]; then
share|improve this answer
    
Correct, but not optimal. I edited the answer for a single test. –  Rich Homolka Apr 9 '13 at 21:12
    
@RichHomolka I edited the post again to show both solutions. Although your solution is more elegant, I feel that mine answers the question better by showing what was wrong with the initial statement. And the explanation with the && operator makes more sense with my example. –  Simon Apr 10 '13 at 5:31
add comment

case statements are designed for precisely this sort of situation. With the example given, something like this:

#!/bin/sh

extension="avi"
case "$extension" in
  avi | mpg )
    echo "I should print out"
    ;;
  * )
    echo "ERROR: File is not an avi or mpg"
    exit 1
    ;;
esac

This has the obvious advantages of being more easy both to expand and to read.

share|improve this answer
    
case is indeed the better solution for this instead of an if. –  ott-- Apr 9 '13 at 19:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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