How can I read user input as an array in Bash?Array Splitting in bashBash reading array in different...

Professor forcing me to attend a conference, I can't afford even with 50% funding

Why restrict private health insurance?

How strong is the axiom of well-ordered choice?

Tabular environment - text vertically positions itself by bottom of tikz picture in adjacent cell

After Brexit, will the EU recognize British passports that are valid for more than ten years?

Is it a Cyclops number? "Nobody" knows!

How to install "rounded" brake pads

How does a sound wave propagate?

Unidentified signals on FT8 frequencies

What is the best index strategy or query SELECT when performing a search/lookup BETWEEN IP address (IPv4 and IPv6) ranges?

What is the orbit and expected lifetime of Crew Dragon trunk?

I am the light that shines in the dark

Should we avoid writing fiction about historical events without extensive research?

Is the differential, dp, exact or not?

What does it take to become a wilderness skills guide as a business?

Insult for someone who "doesn't know anything"

Can I negotiate a patent idea for a raise, under French law?

Why is there an extra space when I type "ls" on the Desktop?

Does an unused member variable take up memory?

What is the oldest European royal house?

std::string vs const std::string& vs std::string_view

Is this Paypal Github SDK reference really a dangerous site?

Why isn't P and P/poly trivially the same?

Is this a crown race?



How can I read user input as an array in Bash?


Array Splitting in bashBash reading array in different formatCant read variable from user input in bashGenerating 2D array in Bash with unknown dimensionBash: Read Typed Input w/ Tab Parsing Into Array, Then Use Array Elements 1-by-1 With GrepHow to trim user input in bash script?Read input for bash scriptProviding a file as a input to an arrayBash pass both array and non-array parameter to functionProper method for storing user input in bash scripts













10















How could I read user input as an array? :)










share|improve this question

























  • I'm presuming you want to read from stdin? My answer will also work with execution like cat war_and_peace.txt | ./array_test.sh.

    – Stefano Palazzo
    Mar 6 '11 at 7:48











  • Or simply ./array_test.sh < war_and_peace.txt.

    – Eliah Kagan
    May 11 '15 at 18:13
















10















How could I read user input as an array? :)










share|improve this question

























  • I'm presuming you want to read from stdin? My answer will also work with execution like cat war_and_peace.txt | ./array_test.sh.

    – Stefano Palazzo
    Mar 6 '11 at 7:48











  • Or simply ./array_test.sh < war_and_peace.txt.

    – Eliah Kagan
    May 11 '15 at 18:13














10












10








10


3






How could I read user input as an array? :)










share|improve this question
















How could I read user input as an array? :)







command-line bash






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 6 '11 at 8:07









Stefano Palazzo

63.6k33183216




63.6k33183216










asked Mar 6 '11 at 7:06









moata_umoata_u

1,48392026




1,48392026













  • I'm presuming you want to read from stdin? My answer will also work with execution like cat war_and_peace.txt | ./array_test.sh.

    – Stefano Palazzo
    Mar 6 '11 at 7:48











  • Or simply ./array_test.sh < war_and_peace.txt.

    – Eliah Kagan
    May 11 '15 at 18:13



















  • I'm presuming you want to read from stdin? My answer will also work with execution like cat war_and_peace.txt | ./array_test.sh.

    – Stefano Palazzo
    Mar 6 '11 at 7:48











  • Or simply ./array_test.sh < war_and_peace.txt.

    – Eliah Kagan
    May 11 '15 at 18:13

















I'm presuming you want to read from stdin? My answer will also work with execution like cat war_and_peace.txt | ./array_test.sh.

– Stefano Palazzo
Mar 6 '11 at 7:48





I'm presuming you want to read from stdin? My answer will also work with execution like cat war_and_peace.txt | ./array_test.sh.

– Stefano Palazzo
Mar 6 '11 at 7:48













Or simply ./array_test.sh < war_and_peace.txt.

– Eliah Kagan
May 11 '15 at 18:13





Or simply ./array_test.sh < war_and_peace.txt.

– Eliah Kagan
May 11 '15 at 18:13










4 Answers
4






active

oldest

votes


















10














Here's one way to do it:



while read line
do
my_array=("${my_array[@]}" $line)
done

echo ${my_array[@]}


If you just run it, it will keep reading from standard-input until you hit Ctrl+D (EOF). Afterwards, the lines you entered will be in my_array. Some may find this code confusing. The body of the loop basically says my_array = my_array + element.



Some interesting pieces of documentation:




  • The Advanced Bash-Scripting Guide has a great chapter on arrays


  • The manpage of the read builtin


  • 15 array examples from thegeekstuff.com







share|improve this answer





















  • 3





    read -r is quite useful/important sometimes... Stefano's link to the "read builtin manpage" explains its purpose...(to prevent backslash interpretation).

    – Peter.O
    Mar 9 '11 at 5:04



















6














Read it using this:



read -a arr


And for printing, use:



for elem in ${arr[@]}
do
echo $elem
done





share|improve this answer

































    2














    And one that doesn't recreate the array each time (though requires bash 3.1 or newer):



    array=()
    while IFS= read -r -p "Next item (end with an empty line): " line; do
    [[ $line ]] || break # break if line is empty
    array+=("$line")
    done

    printf '%sn' "Items read:"
    printf ' «%s»n' "${array[@]}"


    See http://mywiki.wooledge.org/BashFAQ/001 for more.



    And as always, to avoid writing bugs read http://mywiki.wooledge.org/BashGuide and avoid the tldp-guides like the Advanced bash scripting guide.






    share|improve this answer
























    • Nice links... Thanks for pointing out the IFS issue. Without nulling it, 'read' sripts all leading and trailing whitespace... and of course the -r too...

      – Peter.O
      Mar 9 '11 at 5:20





















    0














    How about this one-liner ;)



    arr=( $(cat -) )
    echo ${arr[@]}





    share|improve this answer








    New contributor




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




















      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/3.0/"u003ecc by-sa 3.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
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f29215%2fhow-can-i-read-user-input-as-an-array-in-bash%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









      10














      Here's one way to do it:



      while read line
      do
      my_array=("${my_array[@]}" $line)
      done

      echo ${my_array[@]}


      If you just run it, it will keep reading from standard-input until you hit Ctrl+D (EOF). Afterwards, the lines you entered will be in my_array. Some may find this code confusing. The body of the loop basically says my_array = my_array + element.



      Some interesting pieces of documentation:




      • The Advanced Bash-Scripting Guide has a great chapter on arrays


      • The manpage of the read builtin


      • 15 array examples from thegeekstuff.com







      share|improve this answer





















      • 3





        read -r is quite useful/important sometimes... Stefano's link to the "read builtin manpage" explains its purpose...(to prevent backslash interpretation).

        – Peter.O
        Mar 9 '11 at 5:04
















      10














      Here's one way to do it:



      while read line
      do
      my_array=("${my_array[@]}" $line)
      done

      echo ${my_array[@]}


      If you just run it, it will keep reading from standard-input until you hit Ctrl+D (EOF). Afterwards, the lines you entered will be in my_array. Some may find this code confusing. The body of the loop basically says my_array = my_array + element.



      Some interesting pieces of documentation:




      • The Advanced Bash-Scripting Guide has a great chapter on arrays


      • The manpage of the read builtin


      • 15 array examples from thegeekstuff.com







      share|improve this answer





















      • 3





        read -r is quite useful/important sometimes... Stefano's link to the "read builtin manpage" explains its purpose...(to prevent backslash interpretation).

        – Peter.O
        Mar 9 '11 at 5:04














      10












      10








      10







      Here's one way to do it:



      while read line
      do
      my_array=("${my_array[@]}" $line)
      done

      echo ${my_array[@]}


      If you just run it, it will keep reading from standard-input until you hit Ctrl+D (EOF). Afterwards, the lines you entered will be in my_array. Some may find this code confusing. The body of the loop basically says my_array = my_array + element.



      Some interesting pieces of documentation:




      • The Advanced Bash-Scripting Guide has a great chapter on arrays


      • The manpage of the read builtin


      • 15 array examples from thegeekstuff.com







      share|improve this answer















      Here's one way to do it:



      while read line
      do
      my_array=("${my_array[@]}" $line)
      done

      echo ${my_array[@]}


      If you just run it, it will keep reading from standard-input until you hit Ctrl+D (EOF). Afterwards, the lines you entered will be in my_array. Some may find this code confusing. The body of the loop basically says my_array = my_array + element.



      Some interesting pieces of documentation:




      • The Advanced Bash-Scripting Guide has a great chapter on arrays


      • The manpage of the read builtin


      • 15 array examples from thegeekstuff.com








      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 6 '11 at 8:13

























      answered Mar 6 '11 at 7:46









      Stefano PalazzoStefano Palazzo

      63.6k33183216




      63.6k33183216








      • 3





        read -r is quite useful/important sometimes... Stefano's link to the "read builtin manpage" explains its purpose...(to prevent backslash interpretation).

        – Peter.O
        Mar 9 '11 at 5:04














      • 3





        read -r is quite useful/important sometimes... Stefano's link to the "read builtin manpage" explains its purpose...(to prevent backslash interpretation).

        – Peter.O
        Mar 9 '11 at 5:04








      3




      3





      read -r is quite useful/important sometimes... Stefano's link to the "read builtin manpage" explains its purpose...(to prevent backslash interpretation).

      – Peter.O
      Mar 9 '11 at 5:04





      read -r is quite useful/important sometimes... Stefano's link to the "read builtin manpage" explains its purpose...(to prevent backslash interpretation).

      – Peter.O
      Mar 9 '11 at 5:04













      6














      Read it using this:



      read -a arr


      And for printing, use:



      for elem in ${arr[@]}
      do
      echo $elem
      done





      share|improve this answer






























        6














        Read it using this:



        read -a arr


        And for printing, use:



        for elem in ${arr[@]}
        do
        echo $elem
        done





        share|improve this answer




























          6












          6








          6







          Read it using this:



          read -a arr


          And for printing, use:



          for elem in ${arr[@]}
          do
          echo $elem
          done





          share|improve this answer















          Read it using this:



          read -a arr


          And for printing, use:



          for elem in ${arr[@]}
          do
          echo $elem
          done






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 5 '18 at 11:43

























          answered Jul 22 '15 at 11:21









          ABcDexterABcDexter

          3,2051913




          3,2051913























              2














              And one that doesn't recreate the array each time (though requires bash 3.1 or newer):



              array=()
              while IFS= read -r -p "Next item (end with an empty line): " line; do
              [[ $line ]] || break # break if line is empty
              array+=("$line")
              done

              printf '%sn' "Items read:"
              printf ' «%s»n' "${array[@]}"


              See http://mywiki.wooledge.org/BashFAQ/001 for more.



              And as always, to avoid writing bugs read http://mywiki.wooledge.org/BashGuide and avoid the tldp-guides like the Advanced bash scripting guide.






              share|improve this answer
























              • Nice links... Thanks for pointing out the IFS issue. Without nulling it, 'read' sripts all leading and trailing whitespace... and of course the -r too...

                – Peter.O
                Mar 9 '11 at 5:20


















              2














              And one that doesn't recreate the array each time (though requires bash 3.1 or newer):



              array=()
              while IFS= read -r -p "Next item (end with an empty line): " line; do
              [[ $line ]] || break # break if line is empty
              array+=("$line")
              done

              printf '%sn' "Items read:"
              printf ' «%s»n' "${array[@]}"


              See http://mywiki.wooledge.org/BashFAQ/001 for more.



              And as always, to avoid writing bugs read http://mywiki.wooledge.org/BashGuide and avoid the tldp-guides like the Advanced bash scripting guide.






              share|improve this answer
























              • Nice links... Thanks for pointing out the IFS issue. Without nulling it, 'read' sripts all leading and trailing whitespace... and of course the -r too...

                – Peter.O
                Mar 9 '11 at 5:20
















              2












              2








              2







              And one that doesn't recreate the array each time (though requires bash 3.1 or newer):



              array=()
              while IFS= read -r -p "Next item (end with an empty line): " line; do
              [[ $line ]] || break # break if line is empty
              array+=("$line")
              done

              printf '%sn' "Items read:"
              printf ' «%s»n' "${array[@]}"


              See http://mywiki.wooledge.org/BashFAQ/001 for more.



              And as always, to avoid writing bugs read http://mywiki.wooledge.org/BashGuide and avoid the tldp-guides like the Advanced bash scripting guide.






              share|improve this answer













              And one that doesn't recreate the array each time (though requires bash 3.1 or newer):



              array=()
              while IFS= read -r -p "Next item (end with an empty line): " line; do
              [[ $line ]] || break # break if line is empty
              array+=("$line")
              done

              printf '%sn' "Items read:"
              printf ' «%s»n' "${array[@]}"


              See http://mywiki.wooledge.org/BashFAQ/001 for more.



              And as always, to avoid writing bugs read http://mywiki.wooledge.org/BashGuide and avoid the tldp-guides like the Advanced bash scripting guide.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 8 '11 at 21:40









              geirhageirha

              31.3k95760




              31.3k95760













              • Nice links... Thanks for pointing out the IFS issue. Without nulling it, 'read' sripts all leading and trailing whitespace... and of course the -r too...

                – Peter.O
                Mar 9 '11 at 5:20





















              • Nice links... Thanks for pointing out the IFS issue. Without nulling it, 'read' sripts all leading and trailing whitespace... and of course the -r too...

                – Peter.O
                Mar 9 '11 at 5:20



















              Nice links... Thanks for pointing out the IFS issue. Without nulling it, 'read' sripts all leading and trailing whitespace... and of course the -r too...

              – Peter.O
              Mar 9 '11 at 5:20







              Nice links... Thanks for pointing out the IFS issue. Without nulling it, 'read' sripts all leading and trailing whitespace... and of course the -r too...

              – Peter.O
              Mar 9 '11 at 5:20













              0














              How about this one-liner ;)



              arr=( $(cat -) )
              echo ${arr[@]}





              share|improve this answer








              New contributor




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

























                0














                How about this one-liner ;)



                arr=( $(cat -) )
                echo ${arr[@]}





                share|improve this answer








                New contributor




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























                  0












                  0








                  0







                  How about this one-liner ;)



                  arr=( $(cat -) )
                  echo ${arr[@]}





                  share|improve this answer








                  New contributor




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










                  How about this one-liner ;)



                  arr=( $(cat -) )
                  echo ${arr[@]}






                  share|improve this answer








                  New contributor




                  Quark 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 answer



                  share|improve this answer






                  New contributor




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









                  answered 10 mins ago









                  QuarkQuark

                  101




                  101




                  New contributor




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





                  New contributor





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






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






























                      draft saved

                      draft discarded




















































                      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%2f29215%2fhow-can-i-read-user-input-as-an-array-in-bash%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

                      Why do type traits not work with types in namespace scope?What are POD types in C++?Why can templates only be...

                      Will tsunami waves travel forever if there was no land?Why do tsunami waves begin with the water flowing away...

                      Should I use Docker or LXD?How to cache (more) data on SSD/RAM to avoid spin up?Unable to get Windows File...