You can execute a command on a remote server using
ssh user@host 'the command'
but is there a way to execute the command without quotes?
(I am on BSD and using OpenSSH)
It depends on the command. In general, when one is passing a command to a remote machine, it is necessary to escape any characters in that command that would normally be interpreted by the local shell. At the risk of overgeneralizing, if there are no characters that the local shell would try to interpret, then it is likely that quotes are not necessary. A corollary of this is that if shell characters are correctly escaped (so that the local shell won't interpret them), then a command that otherwise would require quotes can be re-written so that it doesn't require quotes.
Consider trying to capture the remote system's date into a file named
date.out in the home directory of user
user on the remote system
host. One way to do that with quotes is:
ssh user@remote 'date > date.out'
An incorrect attempt to run that command without quotes might be:
ssh user@remote date > date.out
That results in the local shell processing
> date.out leaving the remote ssh command as simply
date command is run remotely, but its output is saved locally. To avoid that, one needs to escape the
ssh user@remote date \> date.out
Having run that command, we can follow up with a second example. Let's inspect the output file, using a quoted command to
ls the file and
cat its contents:
ssh user@remote 'ls -l date.out; cat date.out'
The unquoted command:
ssh user@remote date ls -l date.out; cat date.out
runs only the
ls command remotely. The
cat command is executed locally, because the local shell interpreted the semicolon character as a separator between two commands.
To run the command correctly without quotes, one uses:
ssh user@remote date ls -l date.out\; cat date.out
Similar rules apply when one wants to utilize variable or parameter expansions in a command. If the variable is defined in the local environment, quotes (or escapes) are often not necessary. If the local user
alex issues the command:
ssh user@remote echo $USER
The output will be
alex, because the local value of $USER was expanded into the ssh command before it was sent to the remote host. If instead the command were double-quoted:
ssh user@remote "echo $USER"
The result would be the same, because the local shell will expand variables when enclosed in double quotes. However, either of the commands:
ssh user@remote 'echo $USER'
ssh user@remote echo \$USER
user, because the expansion of the string
$USER is done by the remote host, not the local shell.
Yes, there is:
$ ssh host.example.com echo this is a test this is a test