I've written a bash shell script (code provided below) that gives the user 4 options. However I'm having a little trouble with the code. Right now when they select option 3, to show the date. It loops over and over again. I have to close the terminal window to stop it because it's an infinite loop. How would I prevent this? Also quit doesn't seem to be working either.

If someone could help me out a bit, thanks.

#!/bin/bashe
 echo -n "Name please? "
 read name
 echo "Menu for $name
    1. Display a long listing of the current directory
    2. Display who is logged on the system
    3. Display the current date and time
    4. Quit "
read input
input1="1"
input2="2"
input3=$(date)
input4=$(exit)
while [ "$input" = "3" ]
do
echo "Current date and time: $input3"
done

while [ "$input" = "4" ]
do
echo "Goodbye $input4"
done
link|improve this question
feedback

2 Answers

A compact version:

options=(
    "Display a long listing of the current directory"
    "Display who is logged on the system"
    "Display the current date and time"
    "Quit" 
)

select option in "${options[@]}"; do
    case "$REPLY" in 
        1) ls -l ;;
        2) who ;;
        3) date ;;
        4) break ;;
    esac
done
link|improve this answer
1  
Compact, to the point. May I suggest this line before the select command: PS3="Enter a number (1-4): " – Hai Vu Apr 13 '11 at 5:37
feedback

I guess it's due to the while loop ;)

The value of $input doesn't change inside of the loop. Either you insert something like a read input into the loop or you change the while ... do into a if ... then. If I understand the intention of your script correctly you don't need those while loops where they are now. You need one big while loop covering everything from echo "Menu for $name till the end.

My version of the script would be:

#!/bin/bash
echo -n "Name please? "
read name
input=""
while [ "$input" != "4" ]; do
  echo "Menu for $name
    1. Display a long listing of the current directory
    2. Display who is logged on the system
    3. Display the current date and time
    4. Quit "
  read input
  input1="1"
  input2="2"
  input3=$(date)
  input4=$(exit)
  if [ "$input" = "3" ]; then
    echo "Current date and time: $input3"
  fi

  if [ "$input" = "4" ]; then
    echo "Goodbye $input4"
  fi
done
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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