Find the answer to your Linux question:
Page 1 of 2 1 2 LastLast
Results 1 to 10 of 16
Hi, I'm trying to read the user's input and store them in a list using a while loop. I came up with the following code but it just adds a ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Nov 2012
    Posts
    21

    How to add the info from read into a list?


    Hi, I'm trying to read the user's input and store them in a list using a while loop. I came up with the following code but it just adds a new input each time and deleting the previous input instead of storing them all. Also I'm using -1 to quit the program but current setup will insert the -1 into the list too which I want to avoid.

    I'm new to linux. any guidance is appreciated. Tnks in advance.

    Code:
    #!/bin/bash
    userInput=-99999
    while [ $userInput -ne -1 ]
    do
    echo "Enter any number. Enter -1 to quit"
    read userInput
    myArray=($userInput)
    echo $myArray
    done

  2. #2
    Linux Enthusiast
    Join Date
    Apr 2004
    Location
    UK
    Posts
    682
    Hi there,

    This bash array tutorial suggests your assignment should read something like:

    Code:
    myArray=($myArray $userInput)
    So this will append the userInput rather than replacing the array. You'll also need to wrap the assignment in an if condition to avoid appending the final -1 value, or trim the last value after the loop completes.

    Let us know how you get on.
    To be good, you must first be bad. "Newbie" is a rank, not a slight.

  3. #3
    Just Joined!
    Join Date
    Nov 2012
    Posts
    21
    Hi, tried out the method you mentioned. It lets me store up to 2 inputs only. Meaning, if I enter 10 and then a 1, the 10 stays. If I go on to enter a 3rd input example 2, I get 50 & 2. The 1 is deleted.

  4. #4
    Linux Enthusiast
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    625
    Quote Originally Posted by kakariko81280 View Post
    Hi there,

    This bash array tutorial suggests your assignment should read something like:

    Code:
    myArray=($myArray $userInput)
    So this will append the userInput rather than replacing the array. You'll also need to wrap the assignment in an if condition to avoid appending the final -1 value, or trim the last value after the loop completes.

    Let us know how you get on.
    The problem is that $myArray only references the first item in the array. You need to reference the whole array:
    Code:
    myArray=(${myArray[@]}  $userInput)
    Or more simply use the "append to array" via:
    Code:
    myArray+=($userInput)
    Also the loop could be so much simpler as:
    Code:
    myArray=()
    while read -p "Enter any number (ctrl-d to quit): " userInput; do
         myArray+=($userInput)
    done
    echo 
    echo ${myArray[@]}
    echo "Enter any number. Enter -1 to quit"
    read userInput

  5. #5
    Just Joined!
    Join Date
    Nov 2012
    Posts
    21
    Hi, re adjusted the codes as follows:

    Code:
    #!/bin/bash
    userInput=-99999
    while [ $userInput -ne -1 ]
    do
    echo "Enter any number. Enter -1 to quit"
    read userInput
    myArray+=(${myArray[@]} $userInput)
    echo $myArray
    done
    But the print out is still as follows:

    Enter any number. Enter -1 to quit
    4
    1
    Enter any number. Enter -1 to quit
    5
    1
    Enter any number. Enter -1 to quit
    6
    1
    Enter any number. Enter -1 to quit
    -1
    1

    Am attempting to get a print out like follows:

    1 2 3 4 5 6

    Thanks for help.

  6. #6
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    Here's one way to do it. While in an eternal loop, count the total elements in the array so far, then use that number as the index number of the input number given. That will auto-increment the array for you. I've added a bit to check that the input is a number, too. Give it a whirl.

    Code:
    #!/bin/bash
    declare -a myArray
    while :; do
      while [ -z "$userInput" ]; do
        echo -n "Enter any number. Enter -1 to quit: "
        read userInput
        if [ -n "$userInput" ]; then
          [ "$userInput" == '-1' ] && stop=1 && break
          echo $userInput|grep -q ^[0-9]*$
          if [ $? -ne 0 ]; then
            echo "\`$userInput' is not a number"
            unset userInput
          fi
        fi
      done
      [ -n "$stop" ] && break
      cnt=${#myArray[*]}
      myArray[$cnt]=$userInput
      unset userInput
    done
    echo ${myArray[*]}
    Last edited by atreyu; 11-18-2012 at 02:22 AM. Reason: lengthened my explanation of how it works

  7. #7
    Just Joined!
    Join Date
    Nov 2012
    Posts
    21
    That's pretty advanced for me..

    declare, why u use ;; after while, break, &&, unset all new to me..

  8. #8
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    Quote Originally Posted by keshk View Post
    That's pretty advanced for me..
    it was at one time for me, too, but i've found they are really simple concepts to learn and are great things to know and use when Bash scripting.

    declare, why u use ;; after while, break, &&, unset all new to me..
    i'll try to explain what these are doing:

    declare -a NAME
    Used to signify that a given variable is an array. it helps you when you are looking at your script to know what is a regular variable and what is supposed to be an array. it is not strictly necessary, but declare is useful to do things like declare that a variable must be an integer (-i) or read-only (-r).

    while :;
    The : here is just short-hand for "true", so you could also do while true; do but the colon is quicker to type! Also, while :; basically means "run an eternal loop" (it will be broken out of by logical within the loop).

    break
    Simply means to break out of a for or while loop. Consider these examples:
    Code:
    # break out of for loop
    for i in `seq 1 9`; do echo $i;sleep 1;[ $i -eq 5 ] && break;done
    Code:
    # break out of while loop
    declare -i i=1;while :; do [ $i -eq 5 ] && break;echo $i;sleep 1;let i+=1;done
    in both of those examples, you can remove the [ $i -eq 5 ] && break; portion of the code to see that the loops now run without breaking out.

    &&
    This is a way of saying "and" to run another command after evaluating a first command, but only if the first command returns true. Related to it is the || function, which can be considered "or". Consider this example:
    Code:
    i=1;[ $i -gt 2 ] && echo "$i is greater than 2" || echo "$i is less than or equal to 2"
    change the first part to i=2 and see what happens.

    unset
    If you are in a for or while loop, and you want to reuse a variable, it is wise to empty it first, so that you don't mistakenly re-use the value from a previous iteration of the loop. The unset built-in command simply erases the value from the variable.

    Also, check out the Bash man page, you read up on all the shell built-in functions there:

    Code:
    man bash

  9. #9
    Just Joined!
    Join Date
    Nov 2012
    Posts
    21
    Thanks for explaining. I re adjusted the codes based on the examples so far. One thing still missing, I'm unable to exclude the -1 from my array. Meaning, for example I want the print out to be 1 2 3 4. But instead I'm getting 1 2 3 4 -1 cos I enter -1 to end the loop. I believe I gotta do something like if array[-1] == -1, delete -1. Can't figure out exact code to match. Tnks for help.

    Code:
    #!/bin/sh
    option=0
    myArray=()
    while [ $option -ne -1 ]
    do
    echo "Enter number to add to array. Enter -1 to quit: "
    read option
    myArray+=($option)
    done
    echo ${myArray[*]}

  10. #10
    Trusted Penguin
    Join Date
    May 2011
    Posts
    4,353
    use the handy && operator that you now know about. instead of this line:
    Code:
    myArray+=($option)
    try this line:
    Code:
    [ "$option" != '-1' ] && myArray+=($option)

Page 1 of 2 1 2 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •