How can we check whether the user input equal to one elements of an array?Command substitiution problem,...

Are there any official mechanics for grafts or anything similar?

Defining and changing unknown CRS into WGS84

Reduction of carbamate with LAH

How to write Hanief (my name) in Japanese?

Does the Creighton Method of Natural Family Planning have a failure rate of 3.2% or less?

What is the meaning of "log" in this sentence?

grep pairs of patterns and file

Where can I find a blank outline of Silk Road routes?

How do I break the broom in Untitled Goose Game?

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

Can I use I2C over 2m cables?

D&D Monsters and Copyright

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

Is it fine to ask this kind of question to the corresponding author of a paper?

In Men at Arms, why announce Edward was caught?

Why not build an "approximate" Analytical Engine before the complete one?

Solving a Certainty Equivalent (Decision Analysis) problem

Meaning of A-infinity relations

Why do English transliterations of Arabic names have so many Qs in them?

Modern warfare theory in a medieval setting

Can I color text by using an image, so that the color isn't flat?

Can massive damage kill you while at 0 HP?

'Cheddar goes "good" with burgers?' Can "go" be seen as a verb of the senses?

Can you be promoted and then fired for-cause? (Performance)



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 7 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() {
read -p "${1}: " nm
echo "${array[*]}" | grep -q "<${nm}>" && echo 'true' || 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() {
          read -p "${1}: " nm
          echo "${array[*]}" | grep -q "<${nm}>" && echo 'true' || 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() {
            read -p "${1}: " nm
            echo "${array[*]}" | grep -q "<${nm}>" && echo 'true' || 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() {
              read -p "${1}: " nm
              echo "${array[*]}" | grep -q "<${nm}>" && echo 'true' || 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() {
              read -p "${1}: " nm
              echo "${array[*]}" | grep -q "<${nm}>" && echo 'true' || 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 7 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

                                          Hudson River Historic District Contents Geography History The district today Aesthetics Cultural...

                                          The number designs the writing. Feandra Aversely Definition: The act of ingrafting a sprig or shoot of one...

                                          Ayherre Geografie Demografie Externe links Navigatiemenu43° 23′ NB, 1° 15′ WL43° 23′ NB, 1°...