首页 > 解决方案 > 如何找到谁调用了我的 bash 应用程序

问题描述

这可能看起来是一个愚蠢的简单问题,但我找不到合适的方法来找到调用者。

我有一个可以在不同应用程序中使用的工具。我想记录谁在使用它。

请注意,在采购、使用source(或点快捷方式)时,执行程序是bash(或您指定的 shell)。在这种情况下,只有当您使用 'tool' 时,调用历史记录才会保留在 上${BASH_SOURCE[*]},包括在 上的调用线路${BASH_LINENO[*]}

我希望 BASH_SOURCE 给出一些提示(历史),但是,该工具没有来源,因此在“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: ${*}"

现在,这是客户端调用者

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

这是结果:

$ . ./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

标签: linuxbash

解决方案


这可能对 Linux 有帮助:

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

推荐阅读