zinnadean
zinnadean

Reputation: 33

Bash for loop to execute commands on remote servers

So I have a list of servers with n length. I need to open a connection and edit a file and close it.

Here's what I currently have:

#!/bin/bash

server_list=(a b c d)

for i in "${server[@]}"; do ssh "${server[@]}"; cd /etc; cp file file.bak; perl -pi -i 's/find/replace/g' file; exit; done

The only issue I have is that I can't exit the ssh connection and move on to the next in the array. I have used the -n, -t and -T options to no avail.

Thanks.

Upvotes: 1

Views: 4381

Answers (1)

codeforester
codeforester

Reputation: 42999

Your current code isn't sending any commands to the ssh sessions. Use a heredoc to pass your commands into ssh:

    #!/bin/bash

    server_list=(a b c d)
    for i in "${server_list[@]}"; do
      #
      # As per Charles' suggestion - "bash -s" makes sure the commands
      # would run with Bash rather than the default shell on the remote
      # server.
      #
      # I have left your commands exactly as in your question.
      # They can be written as a single command as per @chepner's recommendation 
      ssh "$i" bash -s << "EOF"
        cd /etc
        cp file file.bak
        perl -pi -i 's/find/replace/g' file
        exit
EOF
    done

Upvotes: 1

Related Questions