Search code examples
linuxbashenvironment-modules

Problem occurs when sourcing bashrc.user in script


I encountered a problem when I was trying to source a .bashrc.user file. It worked fine when I source the file in the terminal, it gave no complaints. But when I tried to do the same in my bash script, it gave some issues. here is how my code looks like:

comm -13 <(sort -u ~/.bashrc.user) <(sort -u ~/my_script/bashrc.user) > bashrc_diff
if [ -s bashrc_diff ]; then
    cat bashrc_diff >> ~/.bashrc.user
    source ~/.bashrc.user
    printf ".bashrc.user has been configured successfully!\n"
else
    printf ".bashrc.user is up-to-date!\n"
fi
rm bashrc_diff
source ~/.bashrc.user

So whenever I execute this code in my script, it gives and error and says that module: command not found. In the .bashrc.user file there are some module commands doing things like module add git/2.22.0 etc. As I mentioned before it works fine when I source it from terminal but complains in the script with the same type of command, what could be the issue here?


Solution

  • When you are using the terminal, you are running an instance of bash which has been initialised a certain way: Startup files will have been executed to configure your environment.

    One of those startup files has caused a shell function module to be defined.

    According to your comment, this function is defined as:

    module(){
        { eval `/app/modules/0/bin/modulecmd bash "$@"` } 2>&1
    }
    

    To stop seeing errors when you run your script, you could look in the startup files for the place that defines module and then run the same commands at the beginning of your script.

    Alternatively, you could try copying just the module function definition above into your script. However, this may lead to other errors later if the code which defines module does additional setup that you do not replicate.

    As well as this, you should note that rearranging the lines of your ~/.bashrc with sort as you are doing only makes sense if the content is solely standalone lines that can be run in any order.