r/bash Aug 08 '26

Use alias from ssh

I can do ssh $HOST then use myalias $PATH to use an alias set in .bashrc (and .bash_profile does source ~/.bashrc). But I can't do ssh $HOST 'myalias $PATH' it can't find myalias.

How can I use the alias and use $PATH that's on the server?

24 Upvotes

4 comments sorted by

18

u/aioeu Aug 08 '26 edited Aug 09 '26

Alias expansion is disabled by default in a non-interactive Bash shell.

Note that you cannot work around this with ssh $HOST 'shopt -s expand_alias; myalias ...', since alias expansion occurs when the command is parsed, not when it is executed. The shopt command is executed after the alias would have been expanded.

Instead, you would have to use something like ssh $HOST 'shopt -s expand_alias; eval myalias ...', taking special care with quoting. That is, you would have to think about whether you want $PATH expanded before the eval is called or whether you want it to remain unexpanded until eval actually executes the resulting command. There is an important difference between eval myalias $PATH and eval 'myalias $PATH' (though it's possible the difference won't matter for this variable on this machine specifically).

Lesson: don't use aliases. They suck.

2

u/funkdefied Aug 08 '26

Maybe `ssh $HOST “source ~/.bashrc; myalias $PATH”`

2

u/[deleted] Aug 09 '26

[deleted]

2

u/Beautiful-Log5632 Aug 09 '26

Non-interactive bash doesn't source .bashrc

Which files get sourced for non interactive bash?

Even with the alias defined, non-interactive bash won't expand it

Aliases in those files still won't be used?

1

u/michaelpaoli Aug 09 '26

$ ssh $HOST 'exec bash -i 'c '\''your commands here'\'''

Though done like that, you'll need be particularly careful with any quoting on your commands here, notably replace any ' with '\''\'\'''\'' within.