'Executing multiple commands on a remote machine via ssh without repeating myself [duplicate]

I wrote a bash command (that's working) to update an IP address on two remote Pihole DNS servers and restart DNS:

NEW_IP=$(hostname -I); \
ssh pi@raspberrypi3 sudo sed -i "s/172.*/'$NEW_IP'nuc8-pc-wsl.localdomain/g" \
  /etc/pihole/custom.list; \
ssh pi@raspberrypi3 sudo pihole restartdns; \
ssh pi@raspberrypi4 sudo sed -i "s/172.*/'$NEW_IP'nuc8-pc-wsl.localdomain/g" \
  /etc/pihole/custom.list; \
ssh pi@raspberrypi4 sudo pihole restartdns

It's great to have it functioning, but it seems like I shouldn't have to repeat commands like:

sudo sed -i "s/172.*/'$NEW_IP'nuc8-pc-wsl.localdomain/g" /etc/pihole/custom.list

and

sudo pihole restartdns

Loading these commands into variables has resulted in requests for the ssh password from the server -- so that can't be right since I have public key authentication setup. I'm already using pairs of single, and double quotes -- so, I'm not sure how to structure this command to be more compact.

I also tried to use, after each sed command:

&& pihole restartdns

so that one ssh would execute both commands on the host, but the response was:

bash: pihole: command not found

Which I take it to mean that part of the command attempted to run on my local machine rather than the server. How does one go about making a command like this more elegant by avoiding repetition?



Solution 1:[1]

Suggesting to combine all ssh commands into single multi-lined command:

NEW_IP=$(hostname -I); 

set -x  #enable debug trace
ssh pi@raspberrypi3  <<< '
sudo -i
sed -i "s/172.*/'$NEW_IP'nuc8-pc-wsl.localdomain/g" /etc/pihole/custom.list
pihole restartdns
sed -i "s/172.*/'$NEW_IP'nuc8-pc-wsl.localdomain/g" /etc/pihole/custom.list
pihole restartdns
'
set +x  #disable debug trace

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1