bash获取在管道符号之前使用的命令 [英] bash get command that was used before pipe symbol

查看:77
本文介绍了bash获取在管道符号之前使用的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于已经使用程序输出的半成品脚本,我还需要用于传递到脚本的程序的名称和参数.

For a half-finished script that already uses the output of a program I also need the name and the parameters of the program that was used to pipe to my script.

所以我这样运行它:是的|./myscript 现在,我需要将是的东西"存储到变量中.

So I run it like this: yay something | ./myscript Now I need to store "yay something" into a variable.

有一种方法可以通过使用 set -o history -o histexpand echo !! echo $ 0来获取先前运行的命令或当前命令.,但这不包括我在管道之前写的内容.

There is a way to to get previous runned commands or the current one by using set -o history -o histexpand and echo !! or echo $0 but that doesn't include what I wrote right before the pipe.

也许您建议将程序的名称及其参数作为参数传递给我的脚本,然后在其中运行,但我不希望这样(

Maybe you would suggest to pass the name of the program and it's parameter to my script as parameters and then run it there but I don't want this (pass a command as an argument to bash script).

推荐答案

更新后的解决方案(以下为旧版本):

#!/bin/bash -i

#get processes
processes=$(> >(ps -f))

echo beginning:
echo "$processes"

#filter bin/bash -i
pac=$(echo "$processes" | sed '1,/bin\/bash -i/!d')
pac=$(echo "$pac" | tail -2 | head -1)


#kill
delete=$(echo $pac | grep -oP "(?<=$USER\s)\w+")
pac=$(echo "$pac" | grep -o -P '(?<=00:00:00).*(?=)')
echo "$delete"
kill -9 "$delete"

#print
echo " "
echo end:
echo "${pac:1}"

注意:当您使用echo,man或cat时,$ pac将为空.

Note: When you use echo, man or cat then $pac will be empty.

旧文本:

感谢查尔斯的巨大努力,他的联系最终使我进入了 processes = $(>>(ps -f)).这是一个工作示例.您可以例如与 vi测试一起使用|./testprocesses (或yay或trizen之类的nano或包助手,但它不适用于echo,man或cat):

Thanks to Charles for his enormous effort and his link that finally led me to processes=$(> >(ps -f)). Here a working example. You can e.g. use it with vi test | ./testprocesses (or nano or package helpers like yay or trizen but it won't work with echo, man nor with cat):

#!/bin/bash -i

#get processes
processes=$(> >(ps -f))

echo beginning:
echo $processes

#filter
pac=$(echo $processes | grep -o -P '(?<=CM).*(?=testprocesses)' | grep -o -P '(?<=D).*(?=testprocesses)' | grep -o -P "(?<=00:00:00).*(?=$USER)")

#kill
delete=$(echo $pac | grep -oP "(?<=$USER\s)\w+")
pac=$(echo $pac | grep -o -P '(?<=00:00:00).*(?=)')
kill -9 $delete

#print
echo " "
echo end:
echo $pac

kill部分是杀死vi实例所必需的,否则它将继续运行并最终干扰脚本的未来执行.

The kill part is necessary to kill the vi instance else it will still be running and eventually interfer with future executions of the script.

这篇关于bash获取在管道符号之前使用的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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