简体   繁体   English

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

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

As shown in this answer , it's possible to use read with Readline ( -e ) in bash to return previous history items by using the up and down keys: 如此答案所示,可以在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

What is the right way to do this in zsh? 在zsh中执行此操作的正确方法是什么? (getting user input on a loop and allowing for up/down key history completion). (在循环中获取用户输入并允许上/下键历史记录完成)。 This doesn't work: 这不起作用:

#! /usr/bin/env zsh

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

done

I think history completion is disabled by default on scripts in zsh. 我认为在zsh中的脚本默认禁用历史记录完成。 Also, I don't want the history to come from the shell, but from the input that is entered in the script. 另外,我不希望历史记录来自shell,而是来自脚本中输入的输入。

I think you're asking for something along these lines... untested 我认为你要求这些方面的东西...... 未经测试

#! /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

[EDIT] Notice I added -i to the first line ( #! ). [编辑]注意我在第一行添加了-i#! )。 It is merely a way to indicate that the shell must be running in interactive mode. 它只是一种表明shell必须以交互模式运行的方法。 The best way to achieve this is to simply execute the script with zsh -i my-script.zsh , because passing arguments to #! 实现此目的的最佳方法是使用zsh -i my-script.zsh执行脚本,因为将参数传递给#! commands differs between Linux and OSX, so it is in principle something one should not rely on. Linux和OSX之间的命令不同,所以它原则上是一个不应该依赖的东西。

Honestly, why don't you just start a new interactive shell using some custom configuration and (should it be necessary) hooks between commands? 老实说,为什么不使用一些自定义配置启动一个新的交互式shell,并且(如果有必要)在命令之间挂钩? The best way to achieve this is likely to just start a new shell using different config files a new history. 实现这一目标的最佳方法是使用不同的配置文件创建一个新的历史记录。

This is a much better way to do this: 这是一个更好的方法:

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

you can then change the script's config file to perform any other customisation you need (different color prompt, no history saving etc). 然后,您可以更改脚本的配置文件以执行您需要的任何其他自定义(不同的颜色提示,无历史记录保存等)。

To actually do things with the user input, you should use one of the many hooks handled by add-zsh-hook 要使用用户输入实际执行操作,您应该使用add-zsh-hook处理的许多钩子之一

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM