Read in an Array
Read in an Array
+ 4 comments a=($(cat)) echo ${a[@]}
+ 6 comments #!bin/ksh i=0 while read line do array[$i]=$line ((i+=1)) done echo ${array[@]}
+ 3 comments How do we loop through all the entries? When do we stop?
+ 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
+ 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 thei
th position in the array. After all input is read, you can print out the entire phrase usingecho "
${array[*]}"or
echo "${array[@]}"
(they are equivolent here).If you are wondering, the
array[$((i++))]
is simply increasing the value ofi
after it is used to refer to thei
th position in the array. It is the same as writing:... do array[$i] ((i++)) ...
Sort 120 Discussions, By:
Please Login in order to post a comment