Bash function defined in .bashrc not available to other scripts

I execute this command frequently.

load_module virtuoso

It works fine in the terminal.

So I put it in a bash script named load.sh, which is executable.

 #!/bin/bash echo "Hello" load_module virtuoso

but when I try to execute it using ./load.sh, it gives this error,

./load.sh: line 3: load_module: command not found

I tried to debug it by putting echo "hello" in the 'load.sh' file. It prints hello on the screen when I execute the file, so the script works fine, I guess. I don't think about what else to try. Thanks

Here is the summary.

een212023@hertz:~/iec_lab1$ ls -la load.sh
-rwxr-xr-x 1 een212023 nogroup 46 Aug 19 17:59 load.sh
een212023@hertz:~/iec_lab1$ cat load.sh
#!/bin/bash
echo "Hello"
load_module virtuoso
een212023@hertz:~/iec_lab1$ load_module virtuoso
een212023@hertz:~/iec_lab1$ ./load.sh
Hello
./load.sh: line 3: load_module: command not found
een212023@hertz:~/iec_lab1$
een212023@hertz:~/iec_lab1$ type -a load_module
load_module is a function
load_module ()
{ if already_loaded $1; then return 0; fi; load_vars_of_module $1; declare -a required_here=("${additional_required[@]}"); declare -a conflicts_here=("${additional_conflicts[@]}"); load_required_modules ${required_here[*]}; unload_conflicting_modules ${conflicts_here[*]}; load_vars_of_module $1; init_all_paths; add_paths ${additional_path[*]}; add_ldpaths ${additional_ldpath[*]}; add_manpaths ${additional_manpath[*]}; add_lmpaths ${additional_lmpath[*]}; exportvars ${additional_exports[*]}; newaliases "${additional_aliases[@]}"; unset ${!additional*}; export MODULES=${MODULES}:$1
}
6

1 Answer

As others have stated, you need to define your functions when loading your script.

I'm doing this by having a script file that contains my "common" functions that I use in scripts in general. Let's call this file /path/to/bash-common.sh - and in your case, this script would contain the function load_module.

Then what I'm doing is to reference this common script in all other scripts, so all my scripts begin like this:

#!/bin/bash
source /path/to/bash-common.sh

In your case, your load.sh would then be:

#!/bin/bash
source /path/to/bash-common.sh
echo "Hello"
load_module virtuoso

You can then also source /path/to/bash-common.sh in your .bashrc if you want to.

In this way, you only have to maintain all your custom functions in one place, and they are accessible anywhere you source this file (including in your interactive shell if you source it in .bashrc).

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like