LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   I need help with "if -else" statement (https://www.linuxquestions.org/questions/linux-newbie-8/i-need-help-with-if-else-statement-590379/)

sjcorp 10-08-2007 08:19 PM

I need help with "if -else" statement
 
I am trying to do a simple file, but I cannot get it to work. Can you please let me know what I may be doing wrong. I am typing this using pico.

#!/bin/bash

echo -n "What is your last name?>"
read text
echo -n "Are you male or female?>"
read sex
if ($sex = "male"); then
echo "Hello Mr. $text"
else
echo "Hello Ms. $text"
fi

This is the output I receive:

What is your last name?>mmmmmmmm
Are you male or female?>male
./morf.test: line 7: male: command not found
Hello Ms. mmmmmmmm

pljvaldez 10-08-2007 08:25 PM

Don't you want a single = instead of -eq? I think "-eq" is for arithmetic only. You're comparing strings...

ehawk 10-08-2007 08:27 PM

I don't program in the language you are using, but it may have something to do with the variable type of "text". Make sure you are making it a string variable and that the -eq operator can act upon string variables. It may be that the variable "male" is being converted to its ascii numeric value and then compared with your entry, or that that -eq cannot act upon the type of variable or the entry you supplied to the read command.

Hope this helps.

chrism01 10-08-2007 08:28 PM

In shell, use the 'wordy' operators eg -eq for numeric comaprisons, and the symbolic eg '=' operators for strings.
http://www.tldp.org/LDP/abs/html/comparison-ops.html

jaseka 10-09-2007 10:41 AM

This code may serve the purpose


Quote:

echo -n "What is your last name?>"
read text
echo -n "Are you male or female?>"
read sex
o -n "What is your last name?>"
read text
echo -n "Are you male or female?>"
read sex
if [ $sex = "male" ]; then
echo "Hello Mr. $text"
else
echo "Hello Ms. $text"
fi

pwc101 10-09-2007 10:53 AM

Unless I am mistaken, you want a == in your if statement, not a single =.
Code:

#!/bin/bash

echo -n "What is your last name?>"
read text
echo -n "Are you male or female?>"
read sex
if [ $sex == "male" ]; then
  echo "Hello Mr. $text"
else
  echo "Hello Ms. $text"
fi

edit: and you need square brackets around an if statement.
edit2: it seems I am mistaken, a single = works fine. Every day's a school day :)

student04 10-09-2007 04:55 PM

Here are some websites to use as reference and as tutorials for scripting in bash:

http://www.panix.com/~elflord/unix/bash-tute.html
http://www.tldp.org/LDP/abs/html/
http://www.telematica.polito.it/mell...in20pages.html

I found these to be quite useful.

Enjoy.


All times are GMT -5. The time now is 12:41 PM.