I have defined a bash function in my ~/.bashrc file. This allows me to use it in shell terminals. However, it does not seem to exist when I call it from within a script. How can I define a bash function to be used by scripts as well?
How to define a Bash function that can be used by different scripts
bash;shell script;function
~/.bash_profile and ~/.bashrc are not read by scripts, and functions are not exported by default. To do so, you can use export -f like so:$ cat > script << 'EOF'#!/bin/bashfooEOF$ chmod a+x script$ ./script./script: line 2: foo: command not found$ foo() { echo works ; } $ export -f foo$ ./scriptworksexport -f foo could also be called in ~/.bash_profile to make this function available to scripts after login. Be warned that export -f is not portable.A better solution would be to source the file containing the function using . file. This is much more portable, and doesn't rely on your environment being set up in a particular way.