LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Loop in Shell Script (https://www.linuxquestions.org/questions/programming-9/loop-in-shell-script-658000/)

delamatrix 07-24-2008 11:48 AM

Loop in Shell Script
 
I'm trying to write a simple shell script that

1.) prompt for input
2.) write the input to a file
3.) then ask the user if he/she wants to input more data
4.) If user selects 'y', then continue to prompt for input
5.) If user selects 'no', then exit script

Below is what I got so far:

tdydte=$(date +"%b-%d-%y")

tfile="prosolv-$tdydte.txt"

echo "Please Scan Item:"
read theitem
echo $theitem >> ~/misc/$tfile

echo "Would you like to scan another item [y/n]?"
read yourch2

until [ $yourch2 = n ]
do
echo "Please Scan your item:"
read theitem2
echo $theitem2 >> ~/misc/$tfile
done

Thanks in advance

-Delamatrix

pixellany 07-24-2008 12:09 PM

I'm not immediately seeing what your question is. Does the existing code work? If not, what does not work correctly?

Eventually, it looks like you need the if / else construct. Here is an example, copied from the Advanced Bash Scripting Guide**:
Code:

if [ $t −lt 5 ]
then
  return 0 # true
else
  return 1 # false
fi

In place of the test ([...]), substitute your test, and in place of the return statements, you would substitute the desired commands.

**Available at http://tldp.org, but I would start with Bash Guide for Beginners (same site)

delamatrix 07-24-2008 12:44 PM

The script works up to the point where the user is prompted to scan an item after they choose 'y'. After that, it just keeps looping at "Please Scan your item:". Instead of looping back to "Would you like to scan another item? [y/n]"

-Delamatrix

jcookeman 07-24-2008 02:52 PM

Of course it won't work that way. You have a loop construct that doesn't contain your prompt for user input on that particular question. So, it will never return to that question. With a little clever use of flow control and functions you can do this easily:

Code:

#!/bin/env bash
FILE="~/misc/prosolv-`date +%b-%d-%y`"
CONTINUE="y"
handle_item()
{
    read -p "Please Scan Item: " ITEM
    echo $ITEM >> $FILE
}

until [ $CONTINUE != y ]
do
    handle_item
    read -p "Would you like to scan another item? [y/n] " CONTINUE
done


delamatrix 07-24-2008 05:20 PM

Thanks a lot for all the input guys! I originally was going to try to use functions, but couldn't figure it out. The script works like a charm now.

-Delamatrix


All times are GMT -5. The time now is 04:28 PM.