11

this answer所示,可以使用bash 中read的 Readline ( -e) 通过使用向上和向下键返回以前的历史记录项:

#! /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,而是来自脚本中输入的输入。

4

1 回答 1

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

[编辑] 注意我添加-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

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

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

于 2015-09-08T08:59:03.637 回答