簡體   English   中英

如何使用zsh在向上和向下箭頭鍵中顯示腳本中的歷史條目?

[英]How to make the up and down arrow keys show history entries in a script using zsh?

如此答案所示,可以在bash中使用帶有Readline( -e )的read來使用向上和向下鍵返回以前的歷史記錄項:

#! /usr/bin/env bash

while IFS="" read -p "input> " -e line; do 
    history -s "$line" # append $line to local history
done

在zsh中執行此操作的正確方法是什么? (在循環中獲取用戶輸入並允許上/下鍵歷史記錄完成)。 這不起作用:

#! /usr/bin/env zsh

while IFS="" vared -p "input> " -c line; do 

done

我認為在zsh中的腳本默認禁用歷史記錄完成。 另外,我不希望歷史記錄來自shell,而是來自腳本中輸入的輸入。

我認為你要求這些方面的東西...... 未經測試

#! /bin/zsh -i

local HISTFILE
# -p push history list into a stack, and create a new list
# -a automatically pop the history list when exiting this scope...
HISTFILE=$HOME/.someOtherZshHistoryFile
fc -ap # read 'man zshbuiltins' entry for 'fc'

while IFS="" vared -p "input> " -c line; do 
   print -S $line # places $line (split by spaces) into the history list...
done

[編輯]注意我在第一行添加了-i#! )。 它只是一種表明shell必須以交互模式運行的方法。 實現此目的的最佳方法是使用zsh -i my-script.zsh執行腳本,因為將參數傳遞給#! Linux和OSX之間的命令不同,所以它原則上是一個不應該依賴的東西。

老實說,為什么不使用一些自定義配置啟動一個新的交互式shell,並且(如果有必要)在命令之間掛鈎? 實現這一目標的最佳方法是使用不同的配置文件創建一個新的歷史記錄。

這是一個更好的方法:

 mkdir ~/abc
 echo "export HISTFILE=$HOME/.someOtherZshHistoryFile;autoload -U compinit; compinit" >! ~/abc/.zshrc
 ZDOTDIR=~/abc/ zsh -i

然后,您可以更改腳本的配置文件以執行您需要的任何其他自定義(不同的顏色提示,無歷史記錄保存等)。

要使用用戶輸入實際執行操作,您應該使用add-zsh-hook處理的許多鈎子之一

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM