ALMOST PERFECT SOLUTION:
if [ -p /dev/stdin ]; then
echo "You piped something to this script!"
echo "Some output of the command you piped:"
read input
echo "$input"
echo "That was all."
pipe=true
else
echo "No input piped to script."
fi
echo "NOTE: If you pipe the echo command into this script, you get wrong info"
echo "This script is a child of PID "$parent_pid": $(tr '\0' ' ' </proc/$parent_pid/cmdline)"
children="$(cat /proc/$parent_pid/task/$parent_pid/children)"
echo "All childs of this: $children"
echo "Check with this process table:"
ps -f
parent_tty="$(ps -o tty= -p $parent_pid)"
echo "tty of the parent should be: $parent_tty"
echo "Based on this, check this process tree:"
ps f | grep "$parent_tty"
wanted_pid=$(echo $children | cut -d' ' -f1)
echo "This is the cmdline for PID $wanted_pid ("$([ -z "$pipe" ] && echo "this script):" || echo "before the pipe | ):")
cmdline="$(tr '\0' ' ' </proc/$wanted_pid/cmdline)"
echo "$cmdline"
echo "Use this outside of a script (might lock your pacman db.lck, add killing code if so):"
echo "$cmdline | tr '\0' ' ' </proc/\$(cat /proc/\$$/task/\$$/children | rev | cut -d' ' -f3 | rev)/cmdline"
echo ""
echo "I will kill $wanted_pid now. You might still see some output:"
sleep 0.1
kill -9 "$wanted_pid"
echo ""
echo "Script is done."
From the first revision which might be a bit easier to grasp:
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.