Reputation: 1926
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
Upvotes: 0
Views: 128
Reputation: 189377
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.
Upvotes: 2