获取最后一个bash命令,包括管道 [英] Get last bash command including pipes

查看:64
本文介绍了获取最后一个bash命令,包括管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,该脚本使用$ BASH_COMMAND检索当前运行的命令.该脚本基本上在做一些逻辑工作,以找出每个tmux会话正在打开的当前命令和文件.一切正常,除非用户运行管道命令(即 cat文件| less ),在这种情况下,$ BASH_COMMAND似乎只在管道之前存储第一个命令.结果,脚本没有将命令显示为 less [file] (这是打开文件的实际程序),而是将其输出为 cat [file]

I wrote a script that's retrieving the currently run command using $BASH_COMMAND. The script is basically doing some logic to figure out current command and file being opened for each tmux session. Everything works great, except when user runs a piped command (i.e. cat file | less), in which case $BASH_COMMAND only seems to store the first command before the pipe. As a result, instead of showing the command as less[file] (which is the actual program that has the file open), the script outputs it as cat[file].

我尝试使用的另一种方法是依靠 history 1 而不是$ BASH_COMMAND.这种选择也有两个问题.首先,它不会像$ BASH_COMMAND那样自动扩展别名,这在某些情况下可能会导致脚本感到困惑(例如,如果我告诉它忽略 ls ,但使用ll (映射到 ls -l <​​/code>),脚本将不会忽略该命令,无论如何都要对其进行处理),并且为每个别名添加额外的条件似乎不是一个干净的解决方案.第二个问题是,我正在使用HISTIGNORE过滤掉一些我仍然希望脚本知道的常见命令,使用历史记录只会使脚本忽略最后一条命令,除非由历史记录对其进行跟踪.

One alternative I tried using is relying on history 1 instead of $BASH_COMMAND. There are a couple issues with this alternative as well. First, it does not auto-expand aliases, like $BASH_COMMAND does, which in some cases could cause the script to get confused (for example, if I tell it to ignore ls, but use ll instead (mapped to ls -l), the script will not ignore the command, processing it anyway), and including extra conditionals for each alias doesn't seem like a clean solution. The second problem is that I'm using HISTIGNORE to filter out some common commands, which I still want the script to be aware of, using history will just make the script ignore the last command unless it's tracked by history.

我还尝试使用 $ {#PIPESTATUS [@]} 来查看数组长度是1(没有管道)还是更高(使用管道,在这种情况下,我将检索历史记录),但似乎总是也只知道1个命令.

I also tried using ${#PIPESTATUS[@]} to see if the array length is 1 (no pipes) or higher (pipes used, in which case I would retrieve the history instead), but it seems to always only be aware of 1 command as well.

有人知道其他可能对我有用的替代方法(例如,另一个变量,该变量将为当前子调用完成后要执行的其他子调用存储$ BASH_COMMAND,或者通过某种方式知道管道是否存在在最后一个命令中使用)?

Is anyone aware of other alternatives that could work for me (such as another variable that would store $BASH_COMMAND for the other subcalls that are to be executed after the current subcall is complete, or some way to be aware if the pipe was used in the last command)?

推荐答案

我认为您将需要对实现进行一些更改,并使用"history"命令使其正常工作.另外,使用命令"alias"检查所有已配置的别名.命令"which"检查命令是否实际存储在任何PATH目录中.祝你好运

i think that you will need to change a bit your implementation and use "history" command to get it to work. Also, use the command "alias" to check all of the configured alias.. the command "which" to check if the command is actually stored in any PATH dir. good luck

这篇关于获取最后一个bash命令,包括管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆