I have some commands that I always use and they are rather hard to remember such as lsof -i -P -n | grep LISTEN
. I would like to create an alias for them that also applies when logged in via ssh on another server. Is this possible?
Asked
Active
Viewed 1,051 times
0

Romeo Mihalcea
- 522
- 1
- 9
- 27
3 Answers
2
This is not possible. You need to define your aliases on the other server.

Gerald Schneider
- 23,274
- 8
- 57
- 89
-
1After logging in to your remote host, run a command that ssh's back to your local machine and collects the aliases from there: `while read -r line; do "$line"; done < $(ssh localuser@localmachine "bash -ic alias")` – Sturban Nov 24 '20 at 22:30
1
Rather than defining your alias on the remote host, define a local alias for doing commands remotely. So instead of doing $ ssh bar@foo
and then execute your lsof -P -i -n | grep LISTEN
you do this on your local machine:
$ alias foolsof='ssh bar@foo "lsof -i -P -n" | grep LISTEN'
$ foolsof
Note that pipe and redirect can be tricky, the grep in the above command is executed on your local machine.

Sturban
- 119
- 4
-
-
Maybe you should look into Ansible then. The above could also be made into a function with an argument for user@host instead of hardcoded bar@foo. – Sturban Nov 25 '20 at 13:32
0
You can't make an alias but you can substitute shell variables into your unattended ssh sessions. I use it to define flags for things in scripts sometimes.
export THAT_COMMAND_YOU_LIKE="aptitude moo"
ssh user@server "sudo $THAT_COMMAND_YOU_LIKE "

Some Linux Nerd
- 3,327
- 3
- 19
- 22
-
same as above. I manage a lot of servers, this wouldn't help my scenario – Romeo Mihalcea Nov 25 '20 at 11:37
-
if you manage a lot of servers you can use something like pssh to do the exact same thing en-mass. Aliases aren't allowed in shell scripts for safety reasons, but you can also substitute flags and stuff like that using shell variables, that you can define either in the script or in the command line before invoking the script. – Some Linux Nerd May 17 '21 at 19:03