how can I find who call my bash application

Viewed 135

This may look a silly simple question, but I can't find the appropriate method to find the caller.

I have a tool that can be used from different applications. I want to record who is using it.

Note that when sourcing, using source (or the dot shortcut), the executing program is bash (or your designated shell). In this case, only if you source 'tool', the calling history will be preserved on ${BASH_SOURCE[*]}, including the calling line on ${BASH_LINENO[*]}.

I expect BASH_SOURCE give some hint (history), however, the tool is not sourced so, there is no references to caller on 'BASH_SOURCE'.

#!/bin/bash
# this is the tool: I'm expecting to have 'client' somewhere
echo "Source ${BASH_SOURCE[*]}"
ps -axj | grep "\s$$\s"
echo "tool: ${*}"

now, this is the client caller

#!/bin/bash
# this is the client
chmod +x ./tool            # I'm making this explicit
./tool this is a test

This is the result:

$ . ./client
Source ./tool
30389 17217 17217 30389 pts/1    17217 S+       0   0:00 /bin/bash ./tool this is a test
17217 17218 17217 30389 pts/1    17217 R+       0   0:00 ps -axj
17217 17219 17217 30389 pts/1    17217 S+       0   0:00 grep \s17217\s
30380 30389 30389 30389 pts/1    17217 Ss       0   0:01 -bash
tool: this is a test
2 Answers

Would adding ps -o comm= -p $PPID to tool do what you're after?

Edit: Adding sample output

tink@box ~/tmp$ ./client 
Source ./tool
15576 15578 15576  9978 pts/3    15576 S+    1000   0:00 /bin/bash ./tool this is a test
tool: this is a test
client

This might help with Linux:

#!/bin/bash
GPPID=$(ps -o ppid= -p $PPID | tr -d ' ')
cat /proc/$GPPID/comm
Related