Split string into array Shellscript
#!/bin/bash
str=a:b:c:d:e
arr=(${str//:/ })
OUTPUT:
echo ${arr[@]}
a b c d e
Combining the answers above into something that worked for me
set -- `echo $PATH|cut -d':' --output-delimiter=" " -f 1-`; for i in "$@"; do echo $i; done
gives
# set -- `echo $PATH|cut -d':' --output-delimiter=" " -f 1-`; for i in "$@"; do echo $i; done
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
#
Found a solution that doesn't require changing the IFS or a loop:
str=a:b:c:d:e
arr=(`echo $str | cut -d ":" --output-delimiter=" " -f 1-`)
output:
echo ${arr[@]}
a b c d e
str=a:b:c:d:e
set -f
IFS=:
ary=($str)
for key in "${!ary[@]}"; do echo "$key ${ary[$key]}"; done
outputs
0 a
1 b
2 c
3 d
4 e
Another (bash) technique:
str=a:b:c:d:e
IFS=: read -ra ary <<<"$str"
This limits the change to the IFS variable only for the duration of the read command.