Shell 如何使用zsh使上下箭头键在脚本中显示历史记录条目?

Shell 如何使用zsh使上下箭头键在脚本中显示历史记录条目?,shell,zsh,history,completion,Shell,Zsh,History,Completion,如中所示,可以在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

如中所示,可以在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呢?实现这一点的最佳方法可能是使用不同的配置文件和新的历史记录启动一个新的shell

这是一种更好的方法:

 mkdir ~/abc
 echo "export HISTFILE=$HOME/.someOtherZshHistoryFile;autoload -U compinit; compinit" >! ~/abc/.zshrc
 ZDOTDIR=~/abc/ zsh -i
然后,您可以更改脚本的配置文件以执行所需的任何其他自定义(不同的颜色提示、无历史记录保存等)


要实际处理用户输入,您应该使用由
addzshhook处理的众多钩子中的一个

谢谢您的回答
setopt interactive
不起作用。确实不起作用。shell启动并运行后,无法设置该标志。我对脚本做了一点修改。在任何情况下,你都应该使用一个普通的交互式shell,没有配置文件,它仍然不起作用(我在OSX上,当我使用箭头键时,会听到一声嘟嘟声)。我之所以不把它作为一个新的shell来运行,是因为这只是一个玩具示例。实际的脚本对用户输入执行其他操作。使用
addzshhook
添加一个钩子,并将函数调用附加到命令,或者在添加到历史记录时执行一些操作。