远程 SSH 命令 - bash 绑定警告:未启用行编辑

not*_*ain 23 ssh bash shell

我正在使用 bash 4.3.11(1) 并安装了以下历史插件(通过.bash_it):

# enter a few characters and press UpArrow/DownArrow
# to search backwards/forwards through the history
bind '"^[[A":history-search-backward'
bind '"^[[B":history-search-forward'
Run Code Online (Sandbox Code Playgroud)

当我登录到交互式会话时一切正常,但是当我通过ssh host 'ls -als'例如运行远程命令时,我看到以下输出:

: ssh host 'ls -als'
/home/ubuntu/.bash_it/plugins/enabled/history.plugin.bash: line 3: bind: warning: line editing not enabled
/home/ubuntu/.bash_it/plugins/enabled/history.plugin.bash: line 4: bind: warning: line editing not enabled
Run Code Online (Sandbox Code Playgroud)

当我echo -e '\0033\0143'在每次绑定调用后修改历史插件时,我不再收到警告,但我的控制台已被清除。不是一个巨大的缺点,但知道一种更简洁的方法来抑制远程命令的这种情况会很好。

# Works, but annoyingly clears console
# enter a few characters and press UpArrow/DownArrow
# to search backwards/forwards through the history
bind '"^[[A":history-search-backward'
echo -e '\0033\0143'
bind '"^[[B":history-search-forward'
echo -e '\0033\0143'
Run Code Online (Sandbox Code Playgroud)

Ken*_*ter 32

ssh host 'ls -als'
Run Code Online (Sandbox Code Playgroud)

当您要求 ssh 在远程系统上运行命令时,ssh 通常不会为远程会话分配 PTY(伪 TTY)。您可以使用 ssh-t来强制它分配一个 tty:

ssh -t host 'ls -als'
Run Code Online (Sandbox Code Playgroud)

如果您不想一直输入,可以将此行添加到本地主机上的“.ssh/config”文件中:

RequestTTY yes
Run Code Online (Sandbox Code Playgroud)

或者,您可以修复远程系统上的“.bashrc”文件,以避免运行假定会话是交互式的命令,而不是交互式的。一种方法是将命令包含在会话具有 TTY 的测试中:

if [ -t 1 ]
then
    # standard output is a tty
    # do interactive initialization
fi
Run Code Online (Sandbox Code Playgroud)


小智 6

有一个交互式会话是不够的bind。例如,emacs shell 提供了一个通过if [ -t 1 ]测试的交互式会话,但它没有行编辑,因此bind您中的任何s~/.bashrc都会生成警告。相反,您可以通过执行以下操作来检查是否启用了行编辑(是否有更简单/更好的方法?):

if [[ "$(set -o | grep 'emacs\|\bvi\b' | cut -f2 | tr '\n' ':')" != 'off:off:' ]]; then
  echo "line editing is on"
fi
Run Code Online (Sandbox Code Playgroud)

  • 更简单的方法是使用 `[[ ${SHELLOPTS} =~ (vi|emacs) ]] && echo 'line-editing on' || echo '行编辑关闭'` (4认同)

Kam*_*ski 6

如果没有行编辑,这些bind命令本身是无害的。抑制警告:

bind '"^[[A":history-search-backward' 2>/dev/null
bind '"^[[B":history-search-forward'  2>/dev/null
Run Code Online (Sandbox Code Playgroud)

这有点不优雅,但它应该可以工作。其他答案不同意最佳/充分测试。我的方法规避了这一点。但它的扩展性不好。单独使用这两个命令应该不会产生很大的差异;但如果你有更多,比如几十个,那么适当的条件可能会更好。