Meh*_*hdi 14 shell bash ssh alias
我想通过 ssh 连接到远程 Ubuntu 计算机,获取 my.bashrc
并运行一个命令,该命令取决于该.bashrc
. 在命令完成后不会关闭的交互式 shell 中的所有内容。
到目前为止我尝试过的是
ssh user@remote_computer -t 'bash -l -c "my_alias;bash"'
Run Code Online (Sandbox Code Playgroud)
要不就
ssh user@remote_computer -t "my_alias;bash"
Run Code Online (Sandbox Code Playgroud)
这适用于一般命令(ls
例如),但是当我尝试运行中定义的别名时,.bashrc
出现错误:
bash: my_alias: command not found
Run Code Online (Sandbox Code Playgroud)
但是当我再次手动编写并运行它时,它起作用了!
那么我怎样才能确保在.bashrc
调用命令之前是源的?
ter*_*don 13
问题是您试图在非交互式 shell 中运行别名。运行时ssh user@computer command
,command
以非交互方式运行。
非交互式 shell 不读取别名(来自 man bash):
当 shell 不是交互式时,别名不会扩展,除非使用 shopt 设置 expand_aliases shell 选项(请参阅下面的 SHELL BUILTIN COMMANDS 下的 shopt 描述)。
如果您再次手动运行它,它会起作用,因为最后一个bash
命令会启动一个交互式 shell,因此您的别名现在可用。
作为替代方案,您可以在远程计算机上启动交互式 shell ( bash -i
) 而不是简单的登录 shell ( bash -l
) 来运行您的别名:
ssh user@remote_computer -t 'bash -ic "my_alias;bash"'
Run Code Online (Sandbox Code Playgroud)
不过,这似乎是一种非常复杂的方法。您还没有解释为什么需要这样做,但请考虑以下替代方案:
只需在远程机器上启动一个普通的登录交互式 shell 并手动运行命令:
user@local $ ssh user@remote
user@remote $ my_alias
Run Code Online (Sandbox Code Playgroud)如果您始终希望在连接到此计算机时运行该别名,请编辑远程计算机的~/.profile
(或~/.bash_profile
,如果存在)并在末尾添加以下行:
my_alias
Run Code Online (Sandbox Code Playgroud)
因为~/.profile
每次启动登录 shell 时都会读取它(ssh
例如,每次通过 连接时),这将导致my_alias
每次连接时都运行。
请注意,默认情况下,登录 shell 读取~/.profile
or~/.bash_profile
并忽略~/.bashrc
。某些发行版(例如 Debian 及其衍生版和 Arch)发行版(例如 Ubuntu)具有其默认~/.profile
或~/.bash_profile
文件源~/.bashrc
,这意味着您在 中定义的别名~/.bashrc
也将在登录 shell 中可用。并非所有发行版都如此,因此您可能必须~/.profile
手动编辑您的源代码~/.bashrc
。另请注意,如果~/.bash_profile
存在,~/.profile
将被 bash 忽略。
我不得不评论我的 .bashrc 中阻止使用别名的部分,并添加了 expand_aliases 命令。这被评论了
# If not running interactively, don't do anything
#case $- in
# *i*) ;;
# *) return;;
#esac
Run Code Online (Sandbox Code Playgroud)
这是添加的
if [ -z "$PS1" ]; then
shopt -s expand_aliases
fi
Run Code Online (Sandbox Code Playgroud)
然后我的命令起作用了:
ssh user@remote_computer -t "my_alias;bash"
Run Code Online (Sandbox Code Playgroud)