We might want to perform some tasks on a remote server (via SSH) as part of a Bash automation script.
This is how it can be done.
Single commands
To execute just one command on a remote server, we can use the following syntax:
ssh host "/scripts/automated-task.sh"
This will execute the automated-task.sh
file located in the /scripts
folder on the remote server.
Multiple commands
Method 1: One line of code
We can run multiple commands on the remote server by separating those commands with ;
or with &&
.
ssh host "cd /scripts; automated-task.sh"
Or
ssh host "cd /scripts && automated-task.sh"
Method 2: Multiple lines of code
Another way to run multiple commands is:
ssh -T host <<'EOF'
cd /scripts
automated-task.sh
EOF
In this method, we write each command on a new line. If we run a lot of long commands, this might be the right choice to create more readable code.
Of course, in all of these examples, replace host
with the actual host defined in the SSH config
file or use the connection details (user@host
).