0

I am writing a shell script to read the input file and process the contents of the file line by line. I was planning to store each line to an array and process the array later as shown below.

#--------------------------------
# Global Variable
file_path="NULL"
set -A array_statements
#--------------------------------
readFileIntoArray()
{
    while IFS= read -r line
    do
        echo "$line"
        array_statements[${#array_statements[*]}+1]="$line"
    done <"$file_path"
}
printTheArray()
{
    for i in ${array_statements[@]}; do 
        echo $i
    done
}
main()
{
    file_path=$1
    readFileIntoArray
    printTheArray
}
main "$@"

The line contains spaces between the words as Hello World How Are You?. When I execute the script, and print the content of the array_statements, the output is

Hello
World
How
Are
You?

How do I assign the variable value which contains spaces to another variable or pass the varaible which contains spaces to another function in KSH.

Thanks

NJMR
  • 1,886
  • 1
  • 27
  • 46

1 Answers1

2

The easiest route forward is probably to scrap your current code and refactor it.

array_statements=()
while read -r line; do
    array_statements+=("$line")
done <"$1"
printf "%s\n" "${array_statements[@]}"

With the code simplified this much, it probably doesn't make much sense to keep anything encapsulated in a separate function.

Notice in particular how missing the quotes around ${array_statements[@]} will break them up into one happy crazy string, losing any array element boundaries.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Collecting your data into an array is very frequently an antipattern. If you don't absolutely need random access, simply processing a single line at a time is going to be vastly more elegant and efficient. – tripleee Nov 23 '17 at 13:18