Search code examples
bashpipestdinfile-descriptor

Determination of a script piping an output into another script


I have 2 scripts. Script a.sh is piping output to script b.sh processing the output as follows:

$ cat a.sh
#!/bin/bash
echo output | ./b.sh  ### piping into STDIN of b.sh script
$
$ cat b.sh
#!/bin/bash
grep output ### reading from STDIN
$
$ ./a.sh
output

Is there any way I can determine in script b.sh from which script it's getting input? I would like b.sh script to find out it's a.sh. I tried to work with content of /proc/$$/fd in combination with lsof but without success.


Solution

  • This may be a silly solution but you can use ps to find the parent process than get the command from that process again using ps.

    Example by by adding this to the b.sh you gave above:

    ps -p $(ps -o ppid= -p $$) -o cmd=
    

    the output when called from the a.sh script was:

    /bin/bash ./a.sh
    

    when called directly from the command line:

    -bash
    

    I suppose you could do it using the /proc/$$ folders to achieve the same thing looking in /proc/$$ get the parentPid and read /proc/$(parentPid)/cmdline to get the same result.

    so this way you would do something like:

    parentPid=$(cat /proc/$$/stat | awk '{print $4}')
    cat /proc/$(parentPid)/cmdline
    

    output when b.sh is called from a.sh:

    /bin/bash./a.sh