3

I'm trying to do something fairly simple, and I'm just coming up short. Here is an example variable I'm trying to work with:

20,80,443,53

The variable is just a string of ports separated by commas. I need to get those into an array.

5 Answers 5

7

Set IFS to , and use the read command with a here-string

IFS=, read -r -a arr <<<"20,80,443,53"
printf "%s\n" "${arr[@]}"

20
80
443
53
Sign up to request clarification or add additional context in comments.

Comments

2

Here is one way:

#!/bin/bash
v="20,80,443,53"
IFS=, a=($v) # Split
echo ${a[0]} # Display
echo ${a[1]}
echo ${a[2]}
echo ${a[3]}

Update

Thanks to gniourf_gniourf for pointing out that IFS was modified as the result of the assignment. Here is my quirky work around. Now I see why others did things differently.

v="20,80,443,53"

PREV_IFS="$IFS" # Save previous IFS
IFS=, a=($v)
IFS="$PREV_IFS" # Restore IFS

echo ${a[0]}
echo ${a[1]}
echo ${a[2]}
echo ${a[3]}

1 Comment

Caution, this will globally set the IFS variable! will bite you in the back if you forget about it.
1
var="20,80,442,53"
IFS=, read -ra ary <<< "$var"
printf "%s\n" "${ary[@]}"
20
80
442
53

Comments

0
Ports=('20','80','443','53');

for e in "${lic4l[@]}"; do
    echo $e

I hope this will help and print the ports in the given variable.

2 Comments

Does this actually answer the question?
yes it will add all of your ports into an array which later you can use for display actually it will be Ports=('20','80','443','53'); for e in "${Ports[@]}"; do echo $e
0

With SED it becomes a one-liner:

a=($(sed 's/,/ /g' <<< "20,80,443,53"))

printf "%s\n" "${a[@]}"
20
80
443
53

Comments

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.