繁体   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