1

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.

2
  • Would it be possible for you to NOT have a backup on your remote box, perform your global replace locally the just do scp file "${server[@]}/etc/" Commented Feb 3, 2017 at 21:45
  • 2
    The important thing to understand here is that ssh "${server[@]}" is a distinct command from cd /etc, and as your code is currently written, cd /etc won't be run until ssh "${server[@]}" exits. Commented Feb 3, 2017 at 21:48

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

17 Comments

Do you really mean to have everything but the EOF (shebang included) four-spaces off the margin? I tried to edit, but think you had something going on concurrently, so we ended up stomping on each other there.
@CharlesDuffy That might have been me; I was trying to remove the -n option from ssh that would have prevented the heredoc from being read.
The entire remote script could be reduced to perl -pi.bak 's/find/replace/g' /etc/file, rending the heredoc unnecessary.
BTW, I'd suggest ssh "$i" "bash -s", so you aren't relying on the user's configured default interpreter. I mean, for all we know they could be using something completely noncompliant like fish.
@CharlesDuffy That's the kind of detail I think one can ignore unless the OP brings it up.
|

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.