Vasiliy Vegas Vasiliy Vegas - 3 months ago 19
Linux Question

After bash script completion, change variable and restart script

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"

Answer

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