Solved

Bash string comparison using "OR"

Posted on 2016-08-24
23
67 Views
Last Modified: 2016-09-03
Hi all!

I am trying to implement a very simple bash check.

I want to verify if my user is using --decode OR --encode, otherwise I want to throw an error

# Checking if selected parameter is one of the available ones
if [ "$1" != "--decode" ] || [ "$1" != "--encode" ]; then
    echo "Error:"
    echo "Please check your option"
    exit 1
fi

Open in new window


The code seems ok to me but it does not work...

What am I missing?
0
Comment
Question by:ltpitt
  • 10
  • 8
  • 3
  • +1
23 Comments
 
LVL 28

Expert Comment

by:Michael Pfister
ID: 41768651
The result of your if is always true , even when you provide the correct parameter.

i.e. "$1" != "--decode"  will be true for --encode

Try:
if [ "$1" = "--decode" ] || [ "$1" = "--encode" ]; then
 --- do what you want
else
    echo "Error:"
    echo "Please check your option"
    exit 1
fi
1
 
LVL 28

Expert Comment

by:Michael Pfister
ID: 41768656
Or use AND (&&) instead of OR (||)
1
 
LVL 4

Expert Comment

by:Abhimanyu Suri
ID: 41769293
echo $var
--encode

if [ "$var" == "--decode" ] || [ "$var" == "--encode" ]; then     echo $var; else  echo "Error: $var ";     echo "Please check your option";     fi
--encode


var="--enco"

if [ "$var" == "--decode" ] || [ "$var" == "--encode" ]; then     echo $var; else  echo "Error: $var ";     echo "Please check your option";     fi

Error: --enco
Please check your option


Now , initial != clause will hold TRUE for all values passed

if [ "$var" != "--decode" ] || [ "$var" != "--encode" ]; then     echo $var; else  echo "Error: $var ";     echo "Please check your option";     fi

--enco

if [ "$var" != "--decode" ] || [ "$var" != "--encode" ]; then     echo $var; else  echo "Error: $var ";     echo "Please check your option";     fi
--encode

&& will Fail too , it will let wrong option through but will fail for right option

if [ "$var" != "--decode" ] && [ "$var" != "--encode" ]; then     echo $var; else  echo "Error: $var ";     echo "Please check your option";     fi

Error: --encode
Please check your option

var="--deco"

f [ "$var" != "--decode" ] && [ "$var" != "--encode" ]; then     echo $var; else  echo "Error: $var ";     echo "Please check your option";     fi
--deco
0
 
LVL 11

Expert Comment

by:tel2
ID: 41777271
Hi ltpitt,

I'm not disrespecting Abhimanyu's answer, but what was wrong with mpfister's answers?  They look excellent to me.

Are you aware that you can split points over more than one post?

The thing is, if experts put their time & skills into helping you out, and give you a "correct" answer, but get no credit for it, then that's not really appreciating their (voluntary) efforts, is it?

If you decide you should split the points now, it's not too late.  You can click the "Request Attention" link at the bottom right of your original post, and ask a moderator to re-open the question so you can award points differently.

tel2
0
 
LVL 1

Author Comment

by:ltpitt
ID: 41777643
@tel2

Hi there!

Did you try Abhimanyu's answer?

Basically, if you put option "a" or option "b" the script will end in the same state.

This is not what I asked for.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41777839
Hi ltpitt,

I didn't do much testing with Abhimanyu's answer.  (I tested mpfister's answer, because mpfister's answer is the one I was mainly talking about.)

If Abhimanyu's answer did not do what you asked for, then why did you give him all the points?
0
 
LVL 1

Author Comment

by:ltpitt
ID: 41777850
Sorry, I mixed the names, I was talking about mpfiester's answer.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41777857
OK.

> "Basically, if you put option "a" or option "b" the script will end in the same state."
So let's say the script is called "code.sh".
if you run:
    ./code.sh --encode
or
    ./code.sh --decode
you want to do your processing, right?

But if you put option "a" like this:
    ./code.sh a
or option "b" like this:
    ./code.sh b
you want an error, (i.e. both "a" and "b" should end in the same state), right?
0
 
LVL 1

Author Comment

by:ltpitt
ID: 41777858
1) If user chooses --encode option the script will launch the decode process
2) If user chooses --decode option the script will launch the decode process
3) If user chooses anything else (no option or any other option) he will get the help menu
0
 
LVL 1

Accepted Solution

by:
ltpitt earned 0 total points
ID: 41777861
This is how I solved the issue without using AND or OR as I wanted, just to be clearer:

# Checking if we have both parameters
if [ $# -ne 2 ]; then
    printf "\nError:\n"
    printf "Check your parameters: both are mandatory\n"
    help
    exit 1
fi

# Checking if file exists
if [ -e "$2" ]; then
    if [ "$1" == "--encode" ]; then
        printf "\nYou choose option: $1\n"
        printf "On File: $2\n"
        encode $2
    elif [ "$1" == "--decode" ]; then
        printf "\nYou choose option: $1\n"
        printf "On File: $2\n"
        decode $2
    else
        # Wrong option specified in script parameter
        printf "\nError:\n"
        printf "Please check your option\n\n"
        help
        exit 1
    fi
else
# Files specified in script parameter does not exist
    printf "\nError:\n"
    printf "File does not exist\n\n"
    help
    exit 1
fi

Open in new window

0
 
LVL 11

Expert Comment

by:tel2
ID: 41777867
OK.  Here is mpfister's code, (with appropriate minor adjustments):

#!/bin/bash

if [ "$1" = "--decode" ] || [ "$1" = "--encode" ]; then
        echo "Processing encode/decode..."
        # --- do what you want
else
        echo "Error:"
        echo "Please check your option"
        exit 1
fi

Open in new window


Here's what happens when I run it:

$ ./code.sh --encode
Processing encode/decode...

$ ./code.sh --decode
Processing encode/decode...

$ ./code.sh --anything-else
Error:
Please check your option

$ ./code.sh
Error:
Please check your option

How does that fail to meet your specifications?
0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
LVL 1

Author Comment

by:ltpitt
ID: 41777874
Yes, it fails.

If you read my previous posts you find details:

1) If user chooses --encode option the script will launch the decode process
2) If user chooses --decode option the script will launch the decode process
3) If user chooses anything else (no option or any other option) he will get the help menu

Open in new window

0
 
LVL 11

Expert Comment

by:tel2
ID: 41777876
Which post numbers are you referring to, please?
0
 
LVL 1

Author Comment

by:ltpitt
ID: 41777878
I added what I said (again) as quote in my previous answer.

It is a numbered list.

Can I ask what are you looking for?

Thanks for your input but I think no further help is needed.
0
 
LVL 28

Expert Comment

by:Michael Pfister
ID: 41777897
Ok, this was your original question:

"I want to verify if my user is using --decode OR --encode, otherwise I want to throw an error"

This is what my sample did.
0
 
LVL 11

Expert Comment

by:tel2
ID: 41777919
Well said, mpfister.


To answer your question, ltpitt:
> "Can I ask what are you looking for?"
Yes you can.  It's pretty clear we're not understanding each other.  I am looking to bridge that misunderstanding, and then if you see my point then I'd hope to see you change the way you split the points so it is more fair.

Your original post gave this requirement:
    > "I want to verify if my user is using --decode OR --encode, otherwise I want to throw an error"
As far as I can see, that is exactly what I have just proved mpfister's code does, in post #41777867 (and repeated below).
In the last hour you have reworded those requirements as follows:
1) If user chooses --encode option the script will launch the DECODE process
2) If user chooses --decode option the script will launch the DECODE process
3) If user chooses anything else (no option or any other option) he will get the help menu

Open in new window

And I think mpfister's code meets those requirements, too (i.e. it performs one process (the "DECODE process") for "--encode" & "--decode" options, and gives an error for all other options).

So, right now I have 2 questions for you:

Q1. Which of the following 4 test results fail to meet the requirements you specified, and please quote which requirement each one fails to meet:

$ ./code.sh --encode
Processing encode/decode...

$ ./code.sh --decode
Processing encode/decode...

$ ./code.sh --anything-else
Error:
Please check your option

$ ./code.sh
Error:
Please check your option


Q2. Which of Abhimanyu's code samples meets all of your requirements, and how?
0
 
LVL 1

Author Comment

by:ltpitt
ID: 41779511
Yes, the question stands still:

Is the user using --encode or is the user using --decode?

I think this is also quite clear if you imagine how the script should work: the encode and decode functions are, clearly, not the same function.

I excuse myself if the wording was not incredibly clear to everyone, that is why I came to Experts Exchange: I was looking for an Expert to help and guide me :)

Thanks to your input I've now understood that the only correct answer to this question is ID: 41777861

I have now requested attention in order to change the correct answer.

Have a great day!
0
 
LVL 1

Author Comment

by:ltpitt
ID: 41779725
I've requested that this question be closed as follows:

Accepted answer: 0 points for ltpitt's comment #a41777861

for the following reason:

In my solution the distinction between --encode and --decode action is taken into account
0
 
LVL 11

Expert Comment

by:tel2
ID: 41779726
Hi ltpitt,

I notice that you didn’t answer my questions Q1 & Q2 from my previous post.

I object to this question being closed in a way which accepts your own post as the answer.  Here's why:

> "I think this is also quite clear if you think at the function of the script itself: the encode and decode functions are, clearly, no the same function.
I excuse myself if the wording was not clear to everyone.
"

It seems that you are the only one to whom this was clear.  The rest of us are not mind readers.

Here are some problems with your reasoning about it being quite clear:

a) Providing different code paths for encode and decode options is not what you asked for in your original post.  Here’s what you asked for:
    "I am trying to implement a very simple bash check.
    I want to verify if my user is using --decode OR --encode, otherwise I want to throw an error
"
That doesn’t tell anyone that you want separate code paths for the 2 functions, and neither did the structure of your code in that original post.

b) Without assuming that you wanted something different from what you asked for, what you asked for is all the experts had to go on at the time they gave their answers, and by the time you changed your specifications, it was too late for them to do anything about it.

c) Whether mpfister’s answers were going to help you handle your (modified) specifications depends on how you write the code.  For example, it could have been done something like this:
if [ "$1" = "--decode" ] || [ "$1" = "--encode" ]; then
    [[ "$1" == "--encode" ]] && echo "encode $2..." || echo "decode $2..."
else
    echo "Error:"
    echo "Please check your option"
    exit 1
fi

Open in new window

d) You didn’t tell us what you were going to do with the encode and decode options after the validation.  For all we knew, you might have just wanted to pass them on to another script, function or program.  For example, here I will add 1 line to the end of mpfister’s 2nd method (see post# 41768656) to do that:
if [ "$1" != "--decode" ] && [ "$1" != "--encode" ]; then
    echo "Error:"
    echo "Please check your option"
    exit 1
fi
encode_decode $1 $2

Open in new window

> “Thanks to your input I've now understood that the only correct answer to this question is ID: 41777861"
I see you are referring to you own answer.  But that answer doesn’t actually answer your original question, in the way you asked it, at all.  Have a careful read of your original question, looking at what you actually asked for, without thinking about what you actually wanted in the end. Your original question appears to be asking for help with validating the options, only.

Regarding your reason for closing this question (i.e. “In my solution the distinction between --encode and --decode action is taken into account”), distinguishing between those 2 options was not requested in your original post.  We’re not mind readers.

> "I excuse myself if the wording was not clear to everyone."
Experts have gone to the trouble of giving you answers to the question in your original post in the way that you asked it.  If you didn’t ask for what you wanted, then that should not mean that they miss out on the credit for answering as it was stated (i.e. give credit where credit is due).

For the future, I suggest you take the time to say exactly what you mean.  This could save a lot of time and avoid frustration for everyone.  For example:
-      You original question was misleading (i.e. “I am trying to implement a very simple bash check.  I want to verify if my user is using --decode OR --encode, otherwise I want to throw an error”).
-      Your original code was misleading, and it seemed to confirm the meaning of your question.
-      When you asked me “Did you try Abhimanyu's answer?”, you meant “Did you try mpfister’s answer?”.  You admitted this in your next post.
-      When you said ‘Basically, if you put option "a" or option "b" the script will end in the same state’, it looks as if you probably meant ‘Basically, if you put option "--encode" or option "--decode" the script will end in the same state’.  For all I knew, “a” & “b” could have been your examples of invalid options.
-      When you wrote “1) If user chooses --encode option the script will launch the decode process”, it looks as if you meant “1) If user chooses --encode option the script will launch the encode process”.  You wrote the same thing in 2 different posts.

Please answer my questions Q1 & Q2 from my previous post.

I propose that at least 300 points be assigned to mpfister's answers ("A" grade), and the remainder to Abhimanyu's answer.

Thanks.
tel2
0
 
LVL 1

Author Comment

by:ltpitt
ID: 41779731
No, I am not interested in answering your questions and not interested in assigning points as you decided.

In fact I am paying for my Experts Exchange membership and the services I get on this site.
That is why I need people able to read and understand even my not perfect requirements and collaborate in order to let me achieve the result I am looking for.

If I was able to write perfect requirements and specifications (interesting comic on the topic: http://www.commitstrip.com/en/2016/08/25/a-very-comprehensive-and-precise-spec/?) I'd be either solving the problem on my own (like I had to do anyway in this case) or go on Stackoverflow asking free questions instead of being here on Experts Exchange paying for the service.

Take care, have a great day!
0
 
LVL 11

Expert Comment

by:tel2
ID: 41780925
Hi ltpitt,

I don't think that paying for membership should be used as an excuse for not awarding points in a fair/reasonable/justifiable way.  You're paying money, but that money doesn't get through to the experts.

What kind of "collaboration" were you expecting?  If you mean the experts should have asked you what you actually meant, then I don't think that is a reasonable expectation, because your initial requirements were clear (and the nature of your original question lined up with the original code you provided).

Your 3 point numbered list of what you later decided you really wanted came too late for anyone to do anything about it.

And now you seem to think it's fair to accept your own answer, and give no credit to those who answered your original question, because you're the only one who really knew what you wanted?

Looking at mpfister's answer, for example, he:
- Explained the cause of the problem,
- Gave a solution,
- Then gave a 2nd post giving an alternative solution.

I'm not sure how he could have been expected to provide a better answer, without guessing that you might mean something you didn't ask for.  But as I think I've demonstrated in points c) & d) in my previous post, it would not be reasonable to expect such a guess, and your question was already clear.

Let's see what the moderators have to say about your attempt to accept your own answer after you changed your spec's.  I hope they assign a moderator who understands bash scripting.

tel2
0
 
LVL 1

Author Comment

by:ltpitt
ID: 41781322
I do understand the kind of communication challenge that you underline and there are limitless questions of way poorer quality on this website.
An outstanding number of them finds real guidance and real help, even if the question's owner could not understand  at all the whole picture of what he was looking for.

This is a fantastic plus.
This is the plus that made me decide about paying for a membership.

For me the whole meaning of this site and of its membership is: "Quickly get in touch with experts in order to solve your IT problems". I've just checked and it seems confirmed by the site's motto: "Tech education on-demand".

Even if my money is not going straight to the Experts it keeps the servers whirring and it is paying the bills. I do not honestly know what's on the plate for the Experts, I am not one of them. What I do believe is that without paying subscribers this site wouldn't even exist.

So, basically, we are facing a support situation where I am the customer.

My question was imho perfectly clear and understandable in English language, the comprehension problem could be connected to my apparently poor understanding of the "or" construct in bash.
Or, if I may, to the Expert's lack of caring in my problem and hurry to get rid of the question and cash the points.

Points of view, right? I do believe I am allowed to have mine.

I wanted to check if my user was using --encode option or --decode option.

Because of the ambiguity (English vs Programming) of the word "or" my clarity was far from perfect and I received (more or less), as an answer, the same code I posted in my own question.
This took me into thinking that the provided input didn't move me closer to the solution at all.
Therefore I thought that the general effort put into understanding the problem was very little.

Again, as I see it, I pay to get my problems fixed by an Expert.

This means that I am entitled to evaluate the help I received even if my specifications were not top notch.
All I can sadly do about that is to excuse myself for my lack of clarity and use your observations to learn about how to be clearer the next time.

What I cannot do is say that the input solved my problem because... It did not.

Bottom line: I do not need to be able to write technically perfect requests, this is the very reason I am paying for the service. I am here searching the promised "Tech education on-demand".
As already explained, if I need to take extra effort in studying a subject or in solving / explaining the problem on my own the whole purpose of this service is simply lost and I need to cancel my 5 years old subscription immediately.

This site has the fantastic perk of saving my time, instead of wasting it.

I tried again to explain myself at best I could.
I hope this solves the comprehension issue we are facing otherwise the advantage of saving time here is starting to fade.

I hope they assign a customer focused moderator who understands English language.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Setting up Secure Ubuntu server on VMware 1.      Insert the Ubuntu Server distribution CD or attach the ISO of the CD which is in the “Datastore”. Note that it is important to install the x64 edition on servers, not the X86 editions. 2.      Power on th…
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Learn how to get help with Linux/Unix bash shell commands. Use help to read help documents for built in bash shell commands.: Use man to interface with the online reference manuals for shell commands.: Use man to search man pages for unknown command…
Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now