linuxnewbee
linuxnewbee

Reputation: 1008

How to parse user input to bash script

I want a script which will restart the defined services on their respective servers. I want to pass parameter as below to the script: eg:

sh execute.sh [server1:nginx,mysqld],[server2:mysqld,apache2],[server3:mongodb,apache2]

So it should go to server1 and restart nginx and mysqld service over there. Then to server2 and should restart mysqld and apache over there and so on so.

I have the script like below:

#!/bin/bash
# create an array of server:services
a=($(echo "$1" | gawk 'BEGIN { FS="[]],[[]" } ; { print $1, $2, $3 }' | tr -d '[]'))
# add a for loop here to iterate values in array with code below
for var in "${a[@]}" ; do
# get server name
server1=$(echo $a[0] | cut -d ':' -f1)
# get your services as space separated
servs1="$(echo $a[0] | cut -d ':' -f2 | tr ',' ' ')"
# loop your services
for s in $servs1; do
  ssh $server1 "service $s restart"
done
done

The above script is only able to grep the first server name and service. Please help to get others.

Original question:

Upvotes: 1

Views: 2145

Answers (2)

Mike Q
Mike Q

Reputation: 7337

Arrays, IFS, and for loops oh my! Million ways to do this. I love arrays so I used them. I wasn't sure if you wanted to call each service individually or all at once so I did it individually. Also You can also easily build a single command to run from this method. You will notice I am changing IFS to handle the commas. I removed the brackets and the , between the servers so you would call it like this:

CALL SCRIPT:

./test2 server1:nginx,mysqld server2:sshd,apache2

CODE:

    #!/bin/bash
    #-- samples: server1:nginx,mysqld server2:mysqld,apache2
    declare -a list
    read -a list <<< "${@}"
    echo ${list[@]}

    for (( i=0; i<${#list[@]}; i++ )) ;do

        IFS=' '
        server=$(echo ${list[$i]} | cut -d: -f1)
        services=$(echo ${list[$i]} | cut -d: -f2)

        IFS=,
        for each in $services ;do
            echo "Go To $server: restart $each"
        done

    done

OUTPUT:

    Go To server1: restart nginx
    Go To server1: restart mysqld
    Go To server2: restart sshd
    Go To server2: restart apache2

Upvotes: 2

tripleee
tripleee

Reputation: 189809

Why don't you simply

while read host services; do
    for service in $services; do
        ssh "$host" service "$service" restart
    done
done <<____HERE
    server1 nginx mysqld
    server2 mysqld apache
    server3 mongodb apache2
____HERE

Upvotes: 1

Related Questions