【问题标题】:How can I have zsh exclude certain commands from history?如何让 zsh 从历史记录中排除某些命令?
【发布时间】:2015-09-21 00:31:01
【问题描述】:

比如说,那些包含“生产”一词的产品?

【问题讨论】:

    标签: zsh zshrc


    【解决方案1】:
    function zshaddhistory() {
        emulate -L zsh
        if [[ $1 != *"production"* ]] ; then
            print -sr -- "${1%%$'\n'}"
            fc -p
        else
            return 1
        fi
    }
    

    将上面的内容放到交互式 shell 启动时将获取的文件中(到 .zshrc 或像我一样从 .zshrc 获取的文件)。

    替代形式(隐式添加到历史):

    function zshaddhistory() {
        emulate -L zsh
        if [[ $1 = *"production"* ]] ; then
            return 1
        fi
    }
    

    。注意:

    print -sr -- "${1%%$'\n'}"
    

    明确地将项目添加到历史记录中。但是如果zshaddhistory 以零退出代码返回,则同样的事情会隐含地执行 zsh,因此如果没有fc -psetopt nohistignoredups nohistignorealldups(这是默认状态),您将在历史记录中看到不需要的重复项。

    emulate -L zsh 是为了确保仿真设置不会介入并改变函数体的解释。我将这一行放在我在 zsh 配置中定义的每个函数的开头。

    【讨论】:

    • 这对我不起作用...我尝试了很多排列。我还测试了分支是否正确输入(if 条件是正确的)。但该命令仍会被载入历史。但这有效:zshaddhistory() { [[ $1 != *production* ]] }
    • @John Bachir 我犯了一个错误:我认为fc -p 与将命令添加到历史记录有关(现在完全不确定它在这里做了什么)。您的变体有效,因为根据帮助 If any of the hook functions return a non-zero value the history line will not be saved, although it lingers in the history until the next line is executed allow you to reuse or edit it immediately..
    • @Julian 看来您要么需要删除这些行要么使用bothprint -srfc -pfc -p 是必需的,否则print 会产生一个重复的条目(如果设置了它,它将被 HIST_IGNORE_DUPS 选项删除,所以你大部分时间都不会看到它)。 IE。我的代码显式地将条目添加到历史记录中,将其删除或替换为 return 0 将隐式执行相同的操作。
    • @Julian 我用更多解释更新了答案。
    • @Rainy 你可能错过了 LF,我的第一个函数包含 ${1%%$'\n'} 是有原因的。
    猜你喜欢
    • 2021-04-12
    • 2021-05-09
    • 1970-01-01
    • 2012-12-11
    • 2011-02-18
    • 2011-03-11
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    相关资源
    最近更新 更多