We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Linux Shell
  3. Arrays in Bash
  4. Read in an Array
  5. Discussions

Read in an Array

Problem
Submissions
Leaderboard
Discussions

Sort 120 Discussions, By:

votes

Please Login in order to post a comment

  • tomade
    5 years ago+ 4 comments
    a=($(cat))
    echo ${a[@]}
    
    28|
    Permalink
    View more Comments..
  • ravimourya
    6 years ago+ 6 comments
    #!bin/ksh
    i=0
    while read line
    do
    array[$i]=$line
    ((i+=1))
    done
    
    echo ${array[@]}
    
    22|
    Permalink
    View more Comments..
  • framirez72
    7 years ago+ 3 comments

    How do we loop through all the entries? When do we stop?

    5|
    Permalink
  • mattphihughes
    7 years ago+ 1 comment

    For folks who want to use an array (which it's pretty obvious is thoroughly unnecessary), you may be interested in the readarray builtin added in bash 4

    Some documentation here for mapfile, which is the same thing by another name

    4|
    Permalink
  • lukehod
    2 years ago+ 1 comment

    Here is my answer following the guidelines of actually reading input into an array first:

    i=0
    
    while read val
    do
        array[$((i++))]=$val
    done
    
    echo "${array[*]}"
    

    We loop through the input line-by-line using the while loop and put the value in the ith position in the array. After all input is read, you can print out the entire phrase using echo "${array[*]}"orecho "${array[@]}" (they are equivolent here).

    If you are wondering, the array[$((i++))] is simply increasing the value of i after it is used to refer to the ith position in the array. It is the same as writing:

    ...
    do
        array[$i]
        ((i++))
    ...
    
    3|
    Permalink
Load more conversations

Need Help?


View top submissions
  • Contest Calendar
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy
  • Request a Feature