How to use Array in Bash Scripting

First we will see what is Array in Linux

If you have been doing shell scripting, you must have definitely came across the term called variable. So when you use a variable, you can add a single name to the variable – In other words one variable can hold only one value.

Example of an Variable

#!/bin/bash
cityname="Berlin"
echo "$cityname"

So if you want to hold names of multiple cities, then you will have to create new variable for each city.

For an Example

cityname01="Berlin"
cityname02="Tokyo"
cityname03="Moscow"
cityname04="Rio"
cityname05="Denver"

However, to ease life we could use a single Array which could hold up all values in a single variable.

To define Array :-

cityname[0]="Berlin"
cityname[1]="Tokyo"
cityname[2]="Moscow"
cityname[3]="Rio"
cityname[4]="Denver"

So here we have stored all city Names in a Array called “cityname”. So now question is how do you access an Array.

You just need to echo it’s number 🙂 Like shown below.

#!/bin/bash
cityname[0]="Berlin"
cityname[1]="Tokyo"
cityname[2]="Moscow"
cityname[3]="Rio"
cityname[4]="Denver"
echo "${cityname[3]}"

So above script will print “Rio” If you want to print all city names then you would use

echo "${cityname[@]}"

OR

echo "${cityname[*]}"

You can copy paste the script below and run it which will help you understand better.

#!/bin/bash
cityname[0]="Berlin"
cityname[1]="Tokyo"
cityname[2]="Moscow"
cityname[3]="Rio"
cityname[4]="Denver"

echo Cities I love are : "${cityname[@]}"

Output would be.

Cities I love are : Berlin Tokyo Moscow Rio Denver

Shell Script to reboot multiple servers.

Here is simple bash script where you can add the server names in the command line and then it will go on rebooting every server which you have listed.

Script Usage:-

[root@server /]# ./server-reboot.sh appserver1 sqlserver1 dataserver1

Above command will reboot appserver1 sqlserver1 and dataserver1, if you have not setup ssh keys it will ask for password.

To use this script create a file called server-reboot.sh and following contents.

#!/bin/bash
for server in "${@}"
do
{
scriptName=$0
scriptPath=$(dirname $0)
script=$scriptPath/boot.txt
command=`base64 -w0 $script`
ssh -t $server "echo $command | base64 -d | sudo bash"
}
done

Create a another file named boot.txt in the same location where you have created server-reboot.sh.

for ((i=03; i>0; i--)); do sleep 1 ; printf "\rREBOOTING SERVER in $i Second. PRESS CTRL + C to cancel " ; done
shutdown -rf now

Save both the files, give execute permissions to server-reboot.sh and start rebooting.

It’s just not reboot script but you can add any commands which you want to run on multiple Linux servers in the file boot.txt

There are many other ways to do the same task but this works best for my environment. Add in comments what works best for you.