1

We have an implementation to set environment for a particular tool with our custom command.

Eg: custom_command tool_name

This command logs the invokation time, user and tool_name in a log file.

And with these logs, we can findout when was a particular tool last used.

Now, users have this habit of putting the command in their login profile.

So, is it possible to findout if a comamnd is invoked by manually typing it on command line or is sourced from another script and if it is, what was the script name?

I have tried multiple ways. All I can findout is the parent script name i.e., the shell.

My understanding is that it is not possible. But I am just trying my luck.

  • Note that the related question is just that (it's not by no means the same). – skyking May 3 '18 at 6:39
  • @Kusalananda I have checked if there is any change in shopt options when sourcing with script vs directly running the script on command line, there are no changes at any options. Any other I can try like shopt? – GP92 May 3 '18 at 7:03
0

In bash scripts I do it like this usually:

#!/bin/bash

if test "$0" != "$BASH_SOURCE"; then
    SOURCED=1
    MY_NAME=$BASH_SOURCE
else
    SOURCED=0
    MY_NAME=$0
fi

# do something here

if test "$SOURCED" = "1"; then
    # use return instead of exit
    return
fi

# do something here only when not sourced
exit
0

I don't think it's entirely possible.

Granted you can find out what the parent process is and what it's command line parameters are, but at the end of the day when running an interactive shell the parent process of the programs executed from startup script is the same as the programs executed interactively.

If it only where execution from the .profile you could detect that by the fact that /etc/bashrc is sourced after that (in that you could put a command to stop ignoring executions from this shell).

Another approach could be to check the starting time of the parent process. Often interactive execution of a command would be done a while after the shell has started while the init scripts will execute shortly after the shell has started.

A more elaborate idea is to replace /bin/bash with a wrapper that controls the sourcing of the startup files in a more customized manner (the idea is similar to the first idea, but to get that you get your command run after .bashrc). I don't know if this is a good idea, but at least you should be really careful if doing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.