w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
bash: convert ' ' delimited strings into array

Set $IFS. Shell uses $IFS variable to determine what the field separators are. By default $IFS is set to the space character. Change it to newline.

#!/bin/bash
names="Netgear
Hon Hai Precision Ind. Co.
Apple"
# Save current IFS
SAVEIFS=$IFS
# Change IFS to new line. 
IFS=$'
'
names=($names)
# Restore IFS
IFS=$SAVEIFS
for (( i=0; i<${#names[@]}; i++ ))
do
    echo "$i: ${names[$i]}"
done

Output

0: Netgear
1: Hon Hai Precision Ind. Co.
2: Apple




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.