Jam Jam - 2 months ago 9x
Linux Question

How to execute a remote alias on a linux box?

Host B has an alias defined

alias command='ps -aef|egrep "a|b"|egrep -v "c|grep|ksh|sshd|ssh|ps |tail|bash|su \-"'

How can I call this alias from box A?

ssh user@B "command"
does not work.


In bash

Define it as a function:

mycommand() {
  ps -aef | \
    egrep "a|b" | \
    egrep -v "c|grep|ksh|sshd|ssh|ps |tail|bash|su -"

...and then tell your shell to emit the source to that function when generating your remote command:

ssh user@B "$(declare -f mycommand); mycommand"

You can do something similar with an alias, but eww:

# define alias locally
alias mycommand='ps -aef|egrep "a|b"|egrep -v "c|grep|ksh|sshd|ssh|ps |tail|bash|su \-"'

ssh user@B bash -s <<EOF
shopt -s expand_aliases  # enable aliases on remote shell
$(alias -p)              # dump all aliases to remote shell
mycommand                # invoke desired alias

Note the expand_aliases shell option: aliases are by default available only in interactive shells, and a shell invoked with a command line passed as an argument is not interactive.

In ksh

Use typeset -f rather than declare -f to list functions:

ssh user@B "$(typeset -f); mycommand"