In Bash, you can convert lines containing spaces into a string array where each line is an element of the array. Here's how you can do it:
readarray (or mapfile)If you have a multi-line string or a file with lines containing spaces, you can use readarray (or its synonym mapfile) to read the lines into an array.
bash# Example multi-line string with spaces input="line one line two with spaces line three" # Use readarray to split into an array readarray -t array <<< "$input" # Print each element of the array for element in "${array[@]}"; do echo "$element" done
readarray -t array <<< "$input" reads the lines of $input into the array array.-t option removes the trailing newline from each line."${array[@]}" expands to all elements of the array, each as a separate word.IFS and readIf you want to read from a file or a command output, you can use IFS (Internal Field Separator) and read:
bash# Example file with lines containing spaces file="example.txt" # Read file into an array IFS=$'\n' read -d '' -ra array < "$file" # Print each element of the array for element in "${array[@]}"; do echo "$element" done
IFS=$'\n' sets the Internal Field Separator to a newline, so read splits on newlines.read -d '' -ra array < "$file" reads the entire file into the array array."${array[@]}" expands to all elements of the array.while loopIf you want to process each line as it is read (e.g., from a file or command output), you can use a while loop:
bash# Example file with lines containing spaces file="example.txt" # Initialize an empty array array=() # Read file line by line while IFS= read -r line; do array+=("$line") done < "$file" # Print each element of the array for element in "${array[@]}"; do echo "$element" done
while IFS= read -r line reads each line of the file into the variable line.array+=("$line") appends each line to the array array."${array[@]}" expands to all elements of the array."${array[@]}" to expand the array, as this preserves spaces and special characters in each element.for line in $(cat file) or similar constructs, as they split on spaces and break lines with spaces into multiple elements.Vibe can make mistakes. Check answers. Learn more