[FIXED] Run Bash script against a Google Compute instance by ssh, from your machine

Issue

I am trying to run a script that is on my machine on a Google Compute instance. I’d like the script to connect in and do its work, and was surprised to see behavior from below:

#!/bin/bash

gcloud compute ssh myinstance

echo "blah" > /tmp/test.txt

This script does connect to myinstance, but it writes /tmp/test.txt on my machine, not the compute instance. The ssh connection remains when the script ends, my terminal is connected.

I had expected it to connect, write the file to the compute instance, and disconnect from ssh. How do I maintain scripts on my machine and run then against various compute instances easily, by ssh? The main use case is going from Mac to Ubuntu.

Solution

The command you want to run on the remote server should be as an argument to ssh:

gcloud compute ssh myinstance 'echo "blah" > /tmp/test.txt'

Answered By – Jakuje

Answer Checked By – Cary Denson (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published