bash get command that was used before pipe symbol

Viewed 1000

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.

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

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).

1 Answers

UPDATED SOLUTION (old below):

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

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

OLD Text:

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

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.

Related