-3

I got a request to pass a list of ip's as an array in a bash script. For example:

./myscript.sh 192.168.0.1,192.168.0.10,192.168.0.15......

The ip's in the above parameter should properly populate the array present in the bash script. I would like it if anyone can show it in conjunction with the getopts utlity.

FYI - I'm fairly new to bash, so please be understanding......

2
  • Unclear what you're really asking. Please provide more details. As it stands, "$@" is sufficient. Commented Nov 5, 2018 at 23:13
  • mywiki.wooledge.org/BashFAQ/050 might help. Commented Nov 6, 2018 at 0:02

1 Answer 1

0

First you need to remove the commas from your input, the sed takes care of this. Then you can create an array with just the var=() syntax.

#! /bin/bash

no_commas=`echo $1 | sed -e 's/,/ /g'`
ip_array=($no_commas)

for addr in ${ip_array[@]}; do
    echo "Address: $addr"
done

Which gives me:

$./bash_array.sh 192.168.1.33,192.168.2.3
Address: 192.168.1.33
Address: 192.168.2.3
Sign up to request clarification or add additional context in comments.

1 Comment

There some good documentation on this here - tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.