如何使用zsh在向上和向下箭头键中显示脚本中的历史条目?

nac*_*cab 11 shell history zsh completion

如此答案所示,可以使用bash中的readReadline(-e)通过使用向上和向下键返回以前的历史记录项:

#! /usr/bin/env bash

while IFS="" read -p "input> " -e line; do 
    history -s "$line" # append $line to local history
done
Run Code Online (Sandbox Code Playgroud)

在zsh中执行此操作的正确方法是什么?(在循环中获取用户输入并允许上/下键历史记录完成).这不起作用:

#! /usr/bin/env zsh

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

done
Run Code Online (Sandbox Code Playgroud)

我认为在zsh中的脚本默认禁用历史记录完成.另外,我不希望历史记录来自shell,而是来自脚本中输入的输入.

Fra*_*sco 2

我认为你正在要求一些类似的东西......未经测试

#! /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
Run Code Online (Sandbox Code Playgroud)

[编辑] 注意我添加-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
Run Code Online (Sandbox Code Playgroud)

然后,您可以更改脚本的配置文件以执行您需要的任何其他自定义(不同的颜色提示、不保存历史记录等)。

要实际处理用户输入,您应该使用由add-zsh-hook