bobmarksie bobmarksie - 1 month ago 9
Linux Question

Bash - combine 2 ssh calls into 1 (with optional and mandatory commands)

I have a script with 2

ssh
commands. The SSH scripts uses SSH to log into a remote server and deletes docker images.

ssh person@someserver.com 'set -x &&

echo "Stop docker images" ;
sudo docker stop $(sudo docker ps -a -q) ;
sudo docker rmi -f $(sudo docker images -q) ;
sudo docker rm -f $(sudo docker ps -a -q)'


Note use of
;
to separate commands (we don't care if one or more of the commands fail).

The 2nd
ssh
command uses SSH to log into the same server, grab a docker compose file and run docker.

ssh person@someserver.com 'set -x &&

export AWS_CONFIG_FILE=/somelocation/myaws.conf &&
aws s3 cp s3://com.somebucket.somewhere/docker-compose/docker-compose.yml . --region us-east-1 &&

echo "Get ECR login credentials and do a docker compose up" &&
sudo $(aws ecr get-login --region us-east-1) &&
sudo /usr/local/bin/docker-compose up -d'


Note use of
&&
to separate commands (this time we do care if one or more of the commands fail as we grab the exit code i.e
exitCode=$?
).

I don't like the fact I have to split this into 2 so my question is can these 2 sections of bash commands be combined into a single SSH call (with both
;
and
&&
combinations)?

Answer
ssh person@someserver.com 'set -x;

   echo "Stop docker images" ;
   sudo docker stop $(sudo docker ps -a -q) ;
   sudo docker rmi -f $(sudo docker images -q) ;
   sudo docker rm -f $(sudo docker ps -a -q) ;

   export AWS_CONFIG_FILE=/somelocation/myaws.conf &&
   aws s3 cp s3://com.somebucket.somewhere/docker-compose/docker-compose.yml . --region us-east-1 &&

   echo "Get ECR login credentials and do a docker compose up" &&
   sudo $(aws ecr get-login --region us-east-1) &&
   sudo /usr/local/bin/docker-compose up -d'
Comments