23

How can I split a string into array in shell script?

I tried with IFS='delimiter' and it works with loops (for, while) but I need an array from that string.

How can I make an array from a string?

Thanks!

4 Answers 4

34
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.

Sign up to request clarification or add additional context in comments.

10 Comments

It doesn't work. Error message say expected "(" in the line where it is ary=($str).
This is specifically bash syntax. What shell are you using? If you script has #!/bin/sh change to #!/bin/bash
how do you invoke your script?
i don't understand (how am i running this?)
@SJunejo, the only array-like data structure in /bin/sh are the positional parameters: set -- $str; for element in "$@"; do echo $element; done. If you really need an array, you need to choose a different tool for the job.
|
28
#!/bin/bash

str=a:b:c:d:e
arr=(${str//:/ })

OUTPUT:

echo ${arr[@]}
a b c d e

Comments

8

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

1 Comment

for ELEMENT in $(echo 'a,b,c' | cut -d ',' --output-delimiter=' ' -f 1-) do echo "$ELEMENT" done
3

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
# 

3 Comments

Using $PATH for a test string is a nice touch, but: way too complicated, and how does this differ from, e.g, zzk's answer?
@greybeard tl;dr It doesn't :) - I found zzk's answer did not quite work for me so adjusted it by the set -- and then collate with useful stuff from the multiple answers given. This was for my own purposes but also share back if others had the same issue
FWIW I needed to run multiple tests against all folders listed in the path - mainly for auditing against privilege escalation issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.