Help with if-else construct


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Help with if-else construct
# 1  
Old 10-31-2010
Help with if-else construct

Hi all

i have been trying to do a small 'question and answer' script using if-else statement and a combination of pipe. I have succeeded in allowing the user to login with user name and password stored in a sequence username/password in a file named "pass" like this:

Code:
echo "please enter your name"
read i
echo "please enter your password"
read j
userName=$i"/"$j

      grep -n $userName $HOME/testing/pass > $HOME/testing/temp

valid=`cut -f2 -d':' $HOME/testing/temp`

if [ $valid = $userName ]
then

echo "success"
else 
echo "failure"
fi

After a successful login, questions and options answers are displayed for the user to choose from example

3.) What is the capital of The United States of America?
a.) Texas
b) Florida
c) Washington D.C
d) Chicago

. The user after selecting the right one (like c in this case) should enter 'p' for previous, 'n' for next question and 'q' to quit the test and then see his result. My challenge is how to direct or redirect the user to any of these options.
I am currently working on a timer for the script using the 'sleep' command.

Please i would be very grateful if someone can help me.

Thanks.

Last edited by Scott; 11-01-2010 at 05:13 PM.. Reason: Please use code tags
# 2  
Old 10-31-2010
Use a case construct.
Pseudo code
Code:
a="a"
n=0
while a <>q
read a   #a can be next, quit or previous
case a=n
  n=n+1
  do question n
case a=q
  display score
  exit
case a=p
  n=n-1
  do question n
endcase  
enddo


Last edited by Scott; 11-01-2010 at 05:14 PM..
# 3  
Old 10-31-2010
Here's an example that might help you out a bit. Not the complete answer, but enough to get you started:

Code:
#!/usr/bin/env ksh

# present the question, four choices then read and compare the answer with 
# the last parm (correct choice). increases the proper counter based on the selection. 
function ask
{
        typeset ans=""

        echo "$1"
        echo "a) $2"
        echo "b) $3"
        echo "c) $4"
        echo "d) $5"

        while true
        do
                printf "Enter your answer: "
                read ans
                case $ans in
                        a|b|c|d)
                                if [[ $ans == $6 ]]
                                then
                                        correct_tally=$(( correct_tally + 1 ))
                                else
                                        incorrect_tally=$(( incorrect_tally + 1 ))
                                fi
                                q=$(( $q + 1 ))
                                return
                                ;;

                        A|B|C|D)
                                echo "your caps-lock seems to be on; please use lowercase letters"
                                ;;

                        *)      echo "invalid response, please try again"
                                ;;
                esac
        done

}

q=0
nquestions=5
while (( $q < $nquestions ))
do
        case $q in
                0)      ask "London is in which country?" "United States" "China" "Canada" "England" "d";;
                1)      ask "The sky is what colour?" blue green grey orange a;;
                2)      ask "Insects have how many legs?" 3 6 9 12 b;;
                3)      ask "Which is the only fruit with the seeds on the outside?" strawberry bananna orange lime a;;
                4)      ask "Which month has just 28 days?" January March February May c;;
        esac
done

echo "your score: $correct_tally correct; $incorrect_tally wrong"

exit

# 4  
Old 11-01-2010
If they are navigating (next previous) through the questions I assume you want to remember their current answer and allow them to change it:
Code:
3.) What is the capital of The United States of America?
  a.) Texas
  b) Florida
  c) Washington D.C
  d) Chicago 
 
Answer (Use N for next question, P for previous): C

I think using arrays to store the questions, options, correct response and the supplied answer will make your coding much easier (Note arrays are numbered from 0):

Code:
$ cat testit
#!/bin/bash
 
QUESTIONS=(
   "What is the capital of The United States of America"
   "The sky is what colour"
)
 
OPTIONS=(
        "Texas|Florida|Washington D.C|Chicago "
        "Blue|Green|Grey|Orange"
)
 
CORRECT=( "C" "A" )
 
 
echo ${QUESTIONS[0]}?
echo ${CORRECT[1]}
 
$ ./testit
What is the capital of The United States of America?
A

Your main loop might end up looking something like this
Code:
QNUM=0
while true
do
   ask $QNUM
   case $? in
       0)  let QNUM=QNUM+1 ;;  # Next
       1)  let QNUM=QNUM-1 ;;  # Prev
       3)  break ;; # Quit/Done
   esac
   # If before first or after last then wrap
   [ $QNUM -ge ${#QUESTIONS[@]} ] && QNUM=0
   [ $QNUM -lt 0 ] && let QNUM=${#QUESTIONS[@]}-1
done
QNUM=0
SCORE=0
while [ $QNUM -lt ${#QUESTIONS[@]} ]
do
    [ "${CORRECT[$QNUM]}" = "${ANSWER[$QNUM]}" ] && let SCORE=SCORE+1
    let QNUM=QNUM+1
done

The function ask would need to be enhanced to get the question and choices from the arrays and return 0 for next, 1 for prev and 3 for quit. It would also have to assign the answers array according to the response given.

If an invalid response is given to the question ask could print "Invalid response: try again" and return 4 (main loop woudn't change the QNUM and would loop around again asking the same question). It just rights it's self at this stage.

Last edited by Chubler_XL; 11-01-2010 at 01:03 AM.. Reason: Fixed typos and added demo main loop
This User Gave Thanks to Chubler_XL For This Post:
# 5  
Old 11-01-2010
Thanks very much guys but am trying to integrate it with my existing lines of code to meet
the needs of the script. These are actually what the entire script should be doing:

The script will be set up in a directory called firstgrade in the user's home directory. Script name is grade. Students should then be given access so they can run it. The program should be as general purpose as possible and as robust as possible. It should display a set of multiple choice questions, read the answer and check whether the answer is right. The overall score for every student should be recorded as well. The interface will be text based and so fairly rudimentary and should look something like:-
.....
3. What is the capital of the United States of America?
a) Florida
b) Chicago
c) Washington D.C
d) none of these
Enter answer
c
Enter question number, N for next question, P for previous question or Q for done
n


At the end it should tell the participant how many questions they got right. The script should check that the person doing the test is who they say they are and that they haven't done the test before. e.g. something like
....
Enter your username
john
Enter your password
12345
You only have one attempt and you have already done the test
....
The script should incorporate a time limit on the test. As well as this grade script, another script called display which will display all the results in either alphabetic order is needed, or numeric order. A separate setup script should copy the grade and display scripts into the firstgrade directory. A timer should also show the student how many minutes remaining and the script should automatically exit and call the display script to show the student his result (right and wrong ones with the corrections) at t=60mins. Users should also be able to view their results later with their username and password, say, one week later.

This is actually the true picture of everything. I will really appreciate if you would help me make this work.

Thanks.
# 6  
Old 11-01-2010
There are several issues with creating this application as as script.
First the script is visible to the user, meaning that if the correct answer is in the script, the student can see the answer.
Secondly scripts do not use cursor control for the screen, so that if the time is displayed, it will stay there until the next time the enter key is pressed.
Assuming that you are running on a Linux system, I would recommend xHarbour.org as an easy to learn database manager with a procedural language.
# 7  
Old 11-01-2010
Quote:
Originally Posted by jgt
There are several issues with creating this application as as script.
First the script is visible to the user, meaning that if the correct answer is in the script, the student can see the answer.
Secondly scripts do not use cursor control for the screen, so that if the time is displayed, it will stay there until the next time the enter key is pressed.
Assuming that you are running on a Linux system, I would recommend xHarbour.org as an easy to learn database manager with a procedural language.
Agreed, scripting is not the best tool for creating production systems but can be quite usefull for quick prototypes and once-offs.

Students being able to read the script and find answers could be an issue here (do they have access to a shell, or is this to be run on login?). One possible work around is to have script owned by another user and allow students to run it via sudo (or have a wraper script that runs the real script with sudo).

Timeout and cursor positioning isn't a problem below is a demo script that prompts for name with 20 second timeout and countdown timer. The constant update is a little bit of an overkill and it typically better done once a minuite, I update every 2 secs here for demo purposes.

Code:
timer()
{
   WAIT=$1
   # PRE - Save position, hide cursor, move to top left
   # POST - Erase rest of line, restore position, view cursor
   PRE="$( tput sc ; tput civis ; tput cup 0 0)"
   POST="$( tput el ; tput rc ; tput cnorm)"
   while [ -d /proc/$WAIT ]
   do
      if [ $SECONDS -gt 20 ]
      then
         kill -14 $WAIT
         break;
      fi
      echo -e "${PRE}Time to go: $(( 20 - $SECONDS ))${POST}\c"
      sleep 2
   done
}
timeout()
{
   echo "Times up - sorry"
}
 
trap "timeout ; exit" 14
clear
echo -e "\n\nEnter your name: \c"
timer $$ &
read name
echo "Your name is $name"


Last edited by Chubler_XL; 11-01-2010 at 02:08 PM.. Reason: Cleanup formatting
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

How would I construct a (possibly simple) IF statement?

Hi all, I thought this would be simple, but I've been having a lot of trouble trying to write this IF statement, if I may ask for help pls: In BASH, how would I construct the if statement: Should ONLY be true if USEROPTscript=="yes"]] AND $mode=="INSTALL" /or/ $mode=="CHANGE" ]]... (3 Replies)
Discussion started by: jmccoughlin
3 Replies

2. Shell Programming and Scripting

Special IF construct syntax in UNIX

Hi, I don't understand && and || in this context. I thought && is for logical 'AND' and || is for logical 'OR'. && echo "Not empty" || echo "Empty" Please help Thank You (5 Replies)
Discussion started by: TomG
5 Replies

3. Shell Programming and Scripting

For loop; how to construct a array with variables

Hi everybody!! Here is the thing; I have a trouble in this simple situation, I'm trying to write an array with all the arguments of a command. I mean, if I have: ./mycommand.sh aa bb cc dd I need to take an array like this: myarray=(aa bb cc dd) So I use a simple for loop like this: for... (4 Replies)
Discussion started by: andresgom
4 Replies

4. Shell Programming and Scripting

Construct path

Hi, I need to construct the below path from the two available directory path, O/P /home/data/test/run/ht/WEB/HTML /home/data/test/run/ht/WEB/JSP /home/data/test/run/ht/WEB/CSS Path:1 ------ /home/data/test/run/ Path:2 ------ /home/data/share/app/01/lang/ht/WEB/HTML... (5 Replies)
Discussion started by: vel4ever
5 Replies

5. UNIX for Dummies Questions & Answers

awk construct unfamiliar to me

Please help me out: I've seen this construct awk '{...}1'several times, like in scrutinizer's today's post awk '{for(i=2;i<=NF;i++)if($i==$1)$i=RS $i}1' infilebut I can't find (manuals, man pages, internet FAQs,...) an explanation of what it does resp. stands for. Any hint is appreciated! (5 Replies)
Discussion started by: RudiC
5 Replies

6. Shell Programming and Scripting

construct a string with X number of spaces

I'd like to create a variable with the value of X number of space( no Perl please), printf seems to work, but , in following example,10 spaces becomes 1 space when assinged to a variable, Why? other solutions are welcome. $printf "=%10s=\n" = = $var=$(printf "=%10s=\n") echo... (4 Replies)
Discussion started by: honglus
4 Replies

7. Shell Programming and Scripting

syntax error in the if construct

Hi can anyone tell me why is this code giving error mode=$1 if ] || ] then echo "MODES:" exit 1 fi Thanks (5 Replies)
Discussion started by: Anteus
5 Replies

8. Shell Programming and Scripting

if-else construct not working

Hi all, Sorry to ask this easy question but I am stuck. In a scenario i am executing one shell script which contains a if - else construct : if ; then echo $line $line >> successful_build.txt else $line >> failed_services.txt fi explaination : if the... (5 Replies)
Discussion started by: bhaskar_m
5 Replies

9. Shell Programming and Scripting

ksh construct

Hi Guys, could someone tell me what this ksh construct does typeset -r PROG_PWD=${0%/*} does I understand the -r for readonly but I would very much appreciate a definitive account of what this will set $PROG_PWD to. If I run this at the cmd line it it gets set to /usr/bin but I would... (2 Replies)
Discussion started by: ajcannon
2 Replies

10. Shell Programming and Scripting

Problem with looping construct

Hi all I have tried to search for this, but keep getting a MySQL db connect error, so am posing the question here, and taking a risk of incurring the wrath of the mods with my first post... I have the following test script: #!/bin/bash HTTPD=`/bin/ps -axcu | /usr/bin/grep httpd... (6 Replies)
Discussion started by: mikie
6 Replies
Login or Register to Ask a Question