There are different ways to run multiple commands on a remote Unix server using SSH. This article shows the most straightforward and easy approach to SSH and runs multiple commands in using the bash shell.
Executing a single command:
ssh [email protected] ls
Executing multiple commands, inlined, isolated with
ssh [email protected] ls; pwd; apt update
Executing a command with
ssh [email protected] sudo apt update sudo: no tty present and no askpass program specified
sudo requires interactive shell, it can be enabled with
ssh -t [email protected] sudo ls /root [sudo] password for user:
Multi-line command with variables expansion
Let's say you have a variable
VAR1 that you want to run on the remote server. For example, let's consider the following snippet:
VAR1="Variable 1" ssh [email protected] ' ls pwd if true; then echo "True" echo $VAR1 # <-- it won't work else echo "False" fi '
Here SSH will not allow us to run that variable with this method. To make variables expansion work, use
VAR1="Variable 1" ssh [email protected] bash -c "' ls pwd if true; then echo $VAR1 else echo "False" fi '"
Multi-line command from local script
stdin redirection to run a local script using SSH. Let's say you have a
script.sh, and it has the following commands.
ls pwd hostname
Now to run it using SSH, use the following snippet:
ssh [email protected] < script.sh
Multi-line command using Heredoc
Heredoc is presumably the most helpful approach to execute multi-line commands on a remote machine. Likewise, variables extension works out-of-the-box.
VAR1="Variable 1" ssh -T [email protected] << EOSSH ls pwd if true; then echo $VAR1 else echo "False" fi EOSSH
If you need to assign variables inside the
heredoc block, put the opening
heredoc in single quotes.
ssh [email protected] <<'EOSSH' VAR1=`pwd` echo $VAR1 VAR2=$(uname -a) echo $VAR2 EOSSH
Using the above snippet, you may get this below warning message:
Pseudo-terminal will not be allocated because stdin is not a terminal.
You can disable by adding
-T parameter to the SSH command.
ssh -T [email protected] <<'EOSSH' VAR1=`pwd` echo $VAR1 VAR2=$(uname -a) echo $VAR2 EOSSH