get the caller script of an exported function

I have a script /usr/bin/test.sh which looks like that:

test_func()
{
    echo "callertest 1:"
    cat /proc/$PPID/cmdline | tr '' ' '
    echo "callertest 2:"
    ps aux | grep $PPID
}

export -f test_func
bash -c test_func

Because "/usr/bin" is in $PATH, i call the script with "test.sh". The function should echo the script's name or better full path, but i havent got any further than getting "bash". Seems to be an issue with scripts which are placed in $PATH.


Instead of using a function, put your code in a script:

#!/bin/bash

echo "callertest 1:"
cat /proc/$PPID/cmdline | tr '' ' '
echo "callertest 2:"
ps aux | grep $PPID

make sure it is executable:

chmod +x test_script.bash

then execute it with xargs :

seq 10 | xargs -n 1 -P $(nproc) ./test_script.bash

这应该涵盖所有情况:

get_scriptname()
{
    SCRIPTFILE=$(readlink -e -- "${0}" 2>/dev/null)
    until [ -e "${SCRIPTFILE}" ] || [ "$_PPID" = "0" ] ; do
        _PPID=$(awk '{print $4}' /proc/${_PPID:-$$}/stat 2>/dev/null)
        CMDLINE=$(awk -F '' '{print $2}' /proc/${_PPID}/cmdline 2>/dev/null)
        READLINK=$(readlink -e -- "${CMDLINE}" 2>/dev/null)
        WHICH=$(which -- "${CMDLINE}" 2>/dev/null)
        SCRIPTFILE=${READLINK:-${WHICH}}
    done
}

test_func()
{
    get_scriptname
    echo "${SCRIPTFILE}: $1"
}

export -f test_func get_scriptname
bash -c "test_func param0"
echo -e "param1nparam2nparam3" | xargs -n 1 -i bash -c "test_func {}"
链接地址: http://www.djcxy.com/p/9742.html

上一篇: 获取bash命令执行的路径

下一篇: 获取导出函数的调用者脚本