Ssh – Execute local alias through ssh on remote server

aliasbashshellssh

I know I can execute a function through SSH on a remote server like so:

$ ssh remote_server "$(declare -f cool_function); cool_function"

I also have some aliases that I would like to execute on remote servers without having to define them on any file sourced on the remote servers, so I can have all my functions and aliases in one place and use them on any remote SSH server.

I thought this would work:

$ alias very_cool_alias='echo A very cool alias'
$ very_cool_alias
A very cool alias
$ ssh remote_server "$(alias very_cool_alias);very_cool_alias"
bash: very_cool_alias: command not found

Although if I check for aliases the alias is there:

$ ssh remote_server "$(alias very_cool_alias);alias"
alias very_cool_alias='echo A very cool alias'

Why the function works but not the alias, although it is passed to the remote SSH server as the last example proves? Any idea on what I'm missing or how can I achieve this?

I have also tried setting the expand_aliases option but still get command not found:

ssh remote_server "shopt -s expand_aliases;$(alias some_alias);some_alias"    

Best Answer

Shell manual tells us:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt ...

However it also mentions

The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed.

This can be tested locally: (ssh is invoking bash -c remotely):

$ bash -c "shopt -s expand_aliases; shopt expand_aliases;alias x=ls; x"
expand_aliases  on
bash: x: command not found

It does help to make it multi-line:

$ bash -c "shopt -s expand_aliases; alias x='echo y'
> x"
y

And this also works with ssh.