How can we check whether the user input equal to one elements of an array?Command substitiution problem, confusedBash reading array in different formatbash: populating array with elements containing spaces and special charactersHow to hide stderr without “muting” user inputprocessing arguments with bash functionHow I can count how many repeated numbers in a file and then organize them by repetitions?Using user input to determine how many times a for loop iteratesModify a list: filter it, and rearrange the values in the resultMatching two files and keeping blocks that contain the matchHow to get bash file to echo differently based on user input?

How do I break the broom in Untitled Goose Game?

Are there any privately owned large commercial airports?

Was Wayne Brady considered a guest star on "Whose Line Is It Anyway?"

Is the text of all UK treaties and laws public?

How to copy the path of current directory in ubuntu 18.04

Comparison of values in dictionary

Are there any official mechanics for grafts or anything similar?

how do you value what your leisure time is worth?

Would my post-apocalyptic US Government be able to work and function properly?

What determines the top speed in ice skating?

How to ride a fish?

My first random password generator

D&D Monsters and Copyright

Can I perform Umrah while on a Saudi Arabian visit e-visa

Rat proofing compost bin but allowing worms in

Find the percentage

Should I withdraw my paper because the Editor is behaving so badly with me?

What does IKEA-like mean?

How can I curtail abuse of the Illusion wizard's Illusory Reality feature?

Sanitise a high score table

Tikz – Box/frame arround Text with interruption

How can we check whether the user input equal to one elements of an array?

I pay for a service, but I miss the broadcast

Why didn't Kes send Voyager home?



How can we check whether the user input equal to one elements of an array?


Command substitiution problem, confusedBash reading array in different formatbash: populating array with elements containing spaces and special charactersHow to hide stderr without “muting” user inputprocessing arguments with bash functionHow I can count how many repeated numbers in a file and then organize them by repetitions?Using user input to determine how many times a for loop iteratesModify a list: filter it, and rearrange the values in the resultMatching two files and keeping blocks that contain the matchHow to get bash file to echo differently based on user input?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









1















Imagine we have an array like this:



declare -a array=( "one" "two" "three" "four" "five" )

for i in "$all[@]"; do
echo "$i"
done


And we can give an input from the user like this:



read -p "Enter a number: " number


I need something to check if the user input matches one of the elements of this array. If not, this should run:



echo "Try again: " 


This process should be repeated until the user input matches to one of the array elements.










share|improve this question









New contributor



msndm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





















  • Is this a homework project?

    – Graham
    8 hours ago











  • No. I just tried many ways but as I'm new learner I did not find a good way.

    – msndm
    8 hours ago






  • 3





    this reads very similar to a homwork problem... What have you tried so far? Have you gotten any errors? Or are you just asking for a handout?

    – j-money
    8 hours ago











  • stackexchange.com/filters/169 might be a better place for this question if its not about Ubuntu.

    – Graham
    8 hours ago












  • I used it but doesn't work

    – msndm
    8 hours ago

















1















Imagine we have an array like this:



declare -a array=( "one" "two" "three" "four" "five" )

for i in "$all[@]"; do
echo "$i"
done


And we can give an input from the user like this:



read -p "Enter a number: " number


I need something to check if the user input matches one of the elements of this array. If not, this should run:



echo "Try again: " 


This process should be repeated until the user input matches to one of the array elements.










share|improve this question









New contributor



msndm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





















  • Is this a homework project?

    – Graham
    8 hours ago











  • No. I just tried many ways but as I'm new learner I did not find a good way.

    – msndm
    8 hours ago






  • 3





    this reads very similar to a homwork problem... What have you tried so far? Have you gotten any errors? Or are you just asking for a handout?

    – j-money
    8 hours ago











  • stackexchange.com/filters/169 might be a better place for this question if its not about Ubuntu.

    – Graham
    8 hours ago












  • I used it but doesn't work

    – msndm
    8 hours ago













1












1








1








Imagine we have an array like this:



declare -a array=( "one" "two" "three" "four" "five" )

for i in "$all[@]"; do
echo "$i"
done


And we can give an input from the user like this:



read -p "Enter a number: " number


I need something to check if the user input matches one of the elements of this array. If not, this should run:



echo "Try again: " 


This process should be repeated until the user input matches to one of the array elements.










share|improve this question









New contributor



msndm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











Imagine we have an array like this:



declare -a array=( "one" "two" "three" "four" "five" )

for i in "$all[@]"; do
echo "$i"
done


And we can give an input from the user like this:



read -p "Enter a number: " number


I need something to check if the user input matches one of the elements of this array. If not, this should run:



echo "Try again: " 


This process should be repeated until the user input matches to one of the array elements.







bash






share|improve this question









New contributor



msndm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



msndm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 8 hours ago









user3140225

2,2468 silver badges22 bronze badges




2,2468 silver badges22 bronze badges






New contributor



msndm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 8 hours ago









msndmmsndm

82 bronze badges




82 bronze badges




New contributor



msndm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




msndm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

















  • Is this a homework project?

    – Graham
    8 hours ago











  • No. I just tried many ways but as I'm new learner I did not find a good way.

    – msndm
    8 hours ago






  • 3





    this reads very similar to a homwork problem... What have you tried so far? Have you gotten any errors? Or are you just asking for a handout?

    – j-money
    8 hours ago











  • stackexchange.com/filters/169 might be a better place for this question if its not about Ubuntu.

    – Graham
    8 hours ago












  • I used it but doesn't work

    – msndm
    8 hours ago

















  • Is this a homework project?

    – Graham
    8 hours ago











  • No. I just tried many ways but as I'm new learner I did not find a good way.

    – msndm
    8 hours ago






  • 3





    this reads very similar to a homwork problem... What have you tried so far? Have you gotten any errors? Or are you just asking for a handout?

    – j-money
    8 hours ago











  • stackexchange.com/filters/169 might be a better place for this question if its not about Ubuntu.

    – Graham
    8 hours ago












  • I used it but doesn't work

    – msndm
    8 hours ago
















Is this a homework project?

– Graham
8 hours ago





Is this a homework project?

– Graham
8 hours ago













No. I just tried many ways but as I'm new learner I did not find a good way.

– msndm
8 hours ago





No. I just tried many ways but as I'm new learner I did not find a good way.

– msndm
8 hours ago




3




3





this reads very similar to a homwork problem... What have you tried so far? Have you gotten any errors? Or are you just asking for a handout?

– j-money
8 hours ago





this reads very similar to a homwork problem... What have you tried so far? Have you gotten any errors? Or are you just asking for a handout?

– j-money
8 hours ago













stackexchange.com/filters/169 might be a better place for this question if its not about Ubuntu.

– Graham
8 hours ago






stackexchange.com/filters/169 might be a better place for this question if its not about Ubuntu.

– Graham
8 hours ago














I used it but doesn't work

– msndm
8 hours ago





I used it but doesn't work

– msndm
8 hours ago










4 Answers
4






active

oldest

votes


















2
















You do not need to loop over the array to check whether a value belongs to it. Also, in this case I would use a recursive call of a function instead of another loop. As I understand correctly you are searching for something like this:



#!/bin/bash

array=( "one" "two" "three" "four" "five" )

function get_input()
read -p "$1: " number
if [[ " $array[*] " == *" $number "* ]]
then
echo 'true';
else
get_input 'Try again' # a recursive call of the function
fi


get_input 'Enter a number' # the initial call of the function


With the [[ test command we searing for exact match == between one string (the left side) and one regular expression (the right side).



  • The expression " $array[*] " will expand our array as a string, surrounded by two spaces, thus each element (even the first and the last) will be surrounded by spaces - try echo '^'" $array[*] "'$'.


  • The regular expression *" $number "* will match to any strung that consist of the value of the variable $number, surrounded by spaces, surrounded by no mater what other characters *.


We can perform such test by some other tools like grep (with suppressed stdout -q, and searching for exact match <...>). Here is one funny version:



#!/bin/bash

array=( "one" "two" "three" "four" "five" )

function get_input() get_input 'Try again'


get_input "Enter a number"





share|improve this answer


































    2
















    Probably all the other answers are more efficient than this one, but I think that this is more beginner-friendly:



    declare -a all=( "one" "two" "three" "four" "five" )

    read -p "Enter a number: " number

    while true; do

    for i in "$all[@]"; do
    if [[ "$number" = "$i" ]]; then
    exit 0
    fi
    done

    read -p "Try again: " number

    done





    share|improve this answer
































      2
















      You can make the array into an associative array instead.



      #!/bin/bash

      declare -A array=([one]=1 [two]=1 [tree]=1 [four]=1 [five]=1)

      m="Guess? "

      while true; do
      read -r -p "$m" i
      [[ $array[$i] == 1 ]] && break || m="Guess again? "
      done

      echo "Good guess!"





      share|improve this answer


































        1
















        #!/bin/bash

        declare -a array=("one" "two" "three" "four" "five")

        number="wrong"

        while [[ ! "$array[@]" =~ "$number" ]]; do
        [[ "$number" != "wrong" ]] && echo "Incorrect"
        read -p "Insert number: " number
        done





        share|improve this answer


























          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "89"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );







          msndm is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded
















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1177947%2fhow-can-we-check-whether-the-user-input-equal-to-one-elements-of-an-array%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2
















          You do not need to loop over the array to check whether a value belongs to it. Also, in this case I would use a recursive call of a function instead of another loop. As I understand correctly you are searching for something like this:



          #!/bin/bash

          array=( "one" "two" "three" "four" "five" )

          function get_input()
          read -p "$1: " number
          if [[ " $array[*] " == *" $number "* ]]
          then
          echo 'true';
          else
          get_input 'Try again' # a recursive call of the function
          fi


          get_input 'Enter a number' # the initial call of the function


          With the [[ test command we searing for exact match == between one string (the left side) and one regular expression (the right side).



          • The expression " $array[*] " will expand our array as a string, surrounded by two spaces, thus each element (even the first and the last) will be surrounded by spaces - try echo '^'" $array[*] "'$'.


          • The regular expression *" $number "* will match to any strung that consist of the value of the variable $number, surrounded by spaces, surrounded by no mater what other characters *.


          We can perform such test by some other tools like grep (with suppressed stdout -q, and searching for exact match <...>). Here is one funny version:



          #!/bin/bash

          array=( "one" "two" "three" "four" "five" )

          function get_input() get_input 'Try again'


          get_input "Enter a number"





          share|improve this answer































            2
















            You do not need to loop over the array to check whether a value belongs to it. Also, in this case I would use a recursive call of a function instead of another loop. As I understand correctly you are searching for something like this:



            #!/bin/bash

            array=( "one" "two" "three" "four" "five" )

            function get_input()
            read -p "$1: " number
            if [[ " $array[*] " == *" $number "* ]]
            then
            echo 'true';
            else
            get_input 'Try again' # a recursive call of the function
            fi


            get_input 'Enter a number' # the initial call of the function


            With the [[ test command we searing for exact match == between one string (the left side) and one regular expression (the right side).



            • The expression " $array[*] " will expand our array as a string, surrounded by two spaces, thus each element (even the first and the last) will be surrounded by spaces - try echo '^'" $array[*] "'$'.


            • The regular expression *" $number "* will match to any strung that consist of the value of the variable $number, surrounded by spaces, surrounded by no mater what other characters *.


            We can perform such test by some other tools like grep (with suppressed stdout -q, and searching for exact match <...>). Here is one funny version:



            #!/bin/bash

            array=( "one" "two" "three" "four" "five" )

            function get_input() get_input 'Try again'


            get_input "Enter a number"





            share|improve this answer





























              2














              2










              2









              You do not need to loop over the array to check whether a value belongs to it. Also, in this case I would use a recursive call of a function instead of another loop. As I understand correctly you are searching for something like this:



              #!/bin/bash

              array=( "one" "two" "three" "four" "five" )

              function get_input()
              read -p "$1: " number
              if [[ " $array[*] " == *" $number "* ]]
              then
              echo 'true';
              else
              get_input 'Try again' # a recursive call of the function
              fi


              get_input 'Enter a number' # the initial call of the function


              With the [[ test command we searing for exact match == between one string (the left side) and one regular expression (the right side).



              • The expression " $array[*] " will expand our array as a string, surrounded by two spaces, thus each element (even the first and the last) will be surrounded by spaces - try echo '^'" $array[*] "'$'.


              • The regular expression *" $number "* will match to any strung that consist of the value of the variable $number, surrounded by spaces, surrounded by no mater what other characters *.


              We can perform such test by some other tools like grep (with suppressed stdout -q, and searching for exact match <...>). Here is one funny version:



              #!/bin/bash

              array=( "one" "two" "three" "four" "five" )

              function get_input() get_input 'Try again'


              get_input "Enter a number"





              share|improve this answer















              You do not need to loop over the array to check whether a value belongs to it. Also, in this case I would use a recursive call of a function instead of another loop. As I understand correctly you are searching for something like this:



              #!/bin/bash

              array=( "one" "two" "three" "four" "five" )

              function get_input()
              read -p "$1: " number
              if [[ " $array[*] " == *" $number "* ]]
              then
              echo 'true';
              else
              get_input 'Try again' # a recursive call of the function
              fi


              get_input 'Enter a number' # the initial call of the function


              With the [[ test command we searing for exact match == between one string (the left side) and one regular expression (the right side).



              • The expression " $array[*] " will expand our array as a string, surrounded by two spaces, thus each element (even the first and the last) will be surrounded by spaces - try echo '^'" $array[*] "'$'.


              • The regular expression *" $number "* will match to any strung that consist of the value of the variable $number, surrounded by spaces, surrounded by no mater what other characters *.


              We can perform such test by some other tools like grep (with suppressed stdout -q, and searching for exact match <...>). Here is one funny version:



              #!/bin/bash

              array=( "one" "two" "three" "four" "five" )

              function get_input() get_input 'Try again'


              get_input "Enter a number"






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 2 hours ago

























              answered 7 hours ago









              pa4080pa4080

              17.6k7 gold badges36 silver badges83 bronze badges




              17.6k7 gold badges36 silver badges83 bronze badges


























                  2
















                  Probably all the other answers are more efficient than this one, but I think that this is more beginner-friendly:



                  declare -a all=( "one" "two" "three" "four" "five" )

                  read -p "Enter a number: " number

                  while true; do

                  for i in "$all[@]"; do
                  if [[ "$number" = "$i" ]]; then
                  exit 0
                  fi
                  done

                  read -p "Try again: " number

                  done





                  share|improve this answer





























                    2
















                    Probably all the other answers are more efficient than this one, but I think that this is more beginner-friendly:



                    declare -a all=( "one" "two" "three" "four" "five" )

                    read -p "Enter a number: " number

                    while true; do

                    for i in "$all[@]"; do
                    if [[ "$number" = "$i" ]]; then
                    exit 0
                    fi
                    done

                    read -p "Try again: " number

                    done





                    share|improve this answer



























                      2














                      2










                      2









                      Probably all the other answers are more efficient than this one, but I think that this is more beginner-friendly:



                      declare -a all=( "one" "two" "three" "four" "five" )

                      read -p "Enter a number: " number

                      while true; do

                      for i in "$all[@]"; do
                      if [[ "$number" = "$i" ]]; then
                      exit 0
                      fi
                      done

                      read -p "Try again: " number

                      done





                      share|improve this answer













                      Probably all the other answers are more efficient than this one, but I think that this is more beginner-friendly:



                      declare -a all=( "one" "two" "three" "four" "five" )

                      read -p "Enter a number: " number

                      while true; do

                      for i in "$all[@]"; do
                      if [[ "$number" = "$i" ]]; then
                      exit 0
                      fi
                      done

                      read -p "Try again: " number

                      done






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 7 hours ago









                      user3140225user3140225

                      2,2468 silver badges22 bronze badges




                      2,2468 silver badges22 bronze badges
























                          2
















                          You can make the array into an associative array instead.



                          #!/bin/bash

                          declare -A array=([one]=1 [two]=1 [tree]=1 [four]=1 [five]=1)

                          m="Guess? "

                          while true; do
                          read -r -p "$m" i
                          [[ $array[$i] == 1 ]] && break || m="Guess again? "
                          done

                          echo "Good guess!"





                          share|improve this answer































                            2
















                            You can make the array into an associative array instead.



                            #!/bin/bash

                            declare -A array=([one]=1 [two]=1 [tree]=1 [four]=1 [five]=1)

                            m="Guess? "

                            while true; do
                            read -r -p "$m" i
                            [[ $array[$i] == 1 ]] && break || m="Guess again? "
                            done

                            echo "Good guess!"





                            share|improve this answer





























                              2














                              2










                              2









                              You can make the array into an associative array instead.



                              #!/bin/bash

                              declare -A array=([one]=1 [two]=1 [tree]=1 [four]=1 [five]=1)

                              m="Guess? "

                              while true; do
                              read -r -p "$m" i
                              [[ $array[$i] == 1 ]] && break || m="Guess again? "
                              done

                              echo "Good guess!"





                              share|improve this answer















                              You can make the array into an associative array instead.



                              #!/bin/bash

                              declare -A array=([one]=1 [two]=1 [tree]=1 [four]=1 [five]=1)

                              m="Guess? "

                              while true; do
                              read -r -p "$m" i
                              [[ $array[$i] == 1 ]] && break || m="Guess again? "
                              done

                              echo "Good guess!"






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited 7 hours ago

























                              answered 8 hours ago









                              bac0nbac0n

                              3736 bronze badges




                              3736 bronze badges
























                                  1
















                                  #!/bin/bash

                                  declare -a array=("one" "two" "three" "four" "five")

                                  number="wrong"

                                  while [[ ! "$array[@]" =~ "$number" ]]; do
                                  [[ "$number" != "wrong" ]] && echo "Incorrect"
                                  read -p "Insert number: " number
                                  done





                                  share|improve this answer





























                                    1
















                                    #!/bin/bash

                                    declare -a array=("one" "two" "three" "four" "five")

                                    number="wrong"

                                    while [[ ! "$array[@]" =~ "$number" ]]; do
                                    [[ "$number" != "wrong" ]] && echo "Incorrect"
                                    read -p "Insert number: " number
                                    done





                                    share|improve this answer



























                                      1














                                      1










                                      1









                                      #!/bin/bash

                                      declare -a array=("one" "two" "three" "four" "five")

                                      number="wrong"

                                      while [[ ! "$array[@]" =~ "$number" ]]; do
                                      [[ "$number" != "wrong" ]] && echo "Incorrect"
                                      read -p "Insert number: " number
                                      done





                                      share|improve this answer













                                      #!/bin/bash

                                      declare -a array=("one" "two" "three" "four" "five")

                                      number="wrong"

                                      while [[ ! "$array[@]" =~ "$number" ]]; do
                                      [[ "$number" != "wrong" ]] && echo "Incorrect"
                                      read -p "Insert number: " number
                                      done






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 7 hours ago









                                      guillermo chamorroguillermo chamorro

                                      7581 silver badge13 bronze badges




                                      7581 silver badge13 bronze badges
























                                          msndm is a new contributor. Be nice, and check out our Code of Conduct.









                                          draft saved

                                          draft discarded

















                                          msndm is a new contributor. Be nice, and check out our Code of Conduct.












                                          msndm is a new contributor. Be nice, and check out our Code of Conduct.











                                          msndm is a new contributor. Be nice, and check out our Code of Conduct.














                                          Thanks for contributing an answer to Ask Ubuntu!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1177947%2fhow-can-we-check-whether-the-user-input-equal-to-one-elements-of-an-array%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                          Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                          199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單