
我正在使用 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'
當我登入互動式會話時,一切都很好,但是當我通過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
當我在每次綁定呼叫後修改歷史記錄插件時,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'
答案1
僅有互動式會話不足以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
答案2
ssh host 'ls -als'
當您要求 ssh 在遠端系統上執行命令時,ssh 通常不會為遠端會話指派 PTY(偽 TTY)。您可以執行 ssh 來-t
強制它指派 tty:
ssh -t host 'ls -als'
如果您不想一直鍵入該內容,可以將此行新增至本機上的「.ssh/config」檔案:
RequestTTY yes
或者,您可以修復遠端系統上的“.bashrc”文件,以避免執行假定會話是互動式的命令,而實際上會話不是互動式的。一種方法是將命令包含在會話具有 TTY 的測試中:
if [ -t 1 ]
then
# standard output is a tty
# do interactive initialization
fi
答案3
如果沒有行編輯,這些bind
命令本身是無害的。抑制警告:
bind '"^[[A":history-search-backward' 2>/dev/null
bind '"^[[B":history-search-forward' 2>/dev/null
這有點不優雅,但它應該可以工作。其他答案不同意最佳/充分測試。我的方法規避了這一點。但它的擴展性不好。單獨使用這兩個命令應該不會產生很大的差異;但如果你有更多,例如幾十個,那麼適當的條件可能會更好。
答案4
我可能只是測試我的 bash 是否是互動的。
if [[ "$-" = *i* ]]
then
debug "interactive mode"
source ~/.bash_lib/bindings
else
debug "non interactive mode"
fi