大网数据广告活动
服务器运维问答

Execute local alias through ssh on remote server

· 52CE 我爱测

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 de…

问题原文

原帖链接 · MauricioRobayo · CC BY-SA 3.0

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"    

已采纳解答

原帖链接 · eckes · CC BY-SA 3.0

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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-05-13)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。