0

I have some working script, in start of which I enter start parameters (server IP, user login and root login), and every time, when I need to restart this script on another server, I need to edit script, to change server IP variable. How can I change this, to enter a bunch of IP addresses in variable(s), maybe in some array and when script finishes with first IP, it goes to second, and so on to the end of IP list?

Script example:

##!/bin/bash

serv_address="xxx.xx.xx.xxx"

"here goes some script body"

2 Answers 2

1

You do indeed want an array, which you can then iterate over with a loop.

serv_address=(xxx.xx.xx.xxx yyy.yy.yyy.yy)

for address in "${serv_address[@]}"; do
    if ! ping -c 1 "$serv_address"; then
        echo "$serv_address is not available" >&2
        continue
    fi
    # Do some stuff here if the address did respond.
done
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works! But my script contains a few checks. Something like: if ! ping -c 1 $serv_address &>/dev/null; then echo "$serv_address is not available" exit 1 fi In case of array - how to rewrite this check that script isn't exit, but goes to next IP address in array?
bash has continue and break commands that work as you might expect from other languages: continue moves directly to the next iteration of the loop, and break exits the loop early.
1

use a text file for storing ips like

$ cat ip.txt
xxx.xx.xx.xxx
xxx.xx.xx.xxx
xxx.xx.xx.xxx
xxx.xx.xx.xxx

then modify your script

#!/bin/bash
while read ip
do
#some command on "$ip"
done<ip.txt # Your text file fed to while loop here

Or use bash array

declare ip_array=( xxx.xx.xx.xxx xxx.xx.xx.xxx xxx.xx.xx.xxx )
for ip in "${ip_array[@]}"
do
#something with "$ip"
done

Both gives you the flexibility to add/delete IP addresses later.

1 Comment

Thanks, it works! But my script contains a few checks. Something like: if ! ping -c 1 $serv_address &>/dev/null; then echo "$serv_address is not available" exit 1 fi In case of array - how to rewrite this check that script isn't exit, but goes to next IP address in array?

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.