Reputation: 13
I have a functions.sh script with a bunch of global functions that i want to use in other scripts. this functions script is written in bash (#!/bin/bash)
Those many scripts had been written over the years, so the older ones or with the #!/bin/sh (which is different from #!/bin/bash in solaris).
My question here is, when you call the functions.sh file (with . /path/to/functions.sh) from within a sh (not bash) script, is the shebang line of "functions.sh" interpreted ?
In a nutshell, can you call a bash written function script from another shell-type script (with proper shebang lines in both) ?
Thanks !
Upvotes: 1
Views: 509
Reputation: 85560
As long as you want to use the function you need to source the scripts and not execute it
source /path/to/functions.sh
or as per the POSIX
standards, do
. ./path/to/functions.sh
from within the sh
script, which is equivalent to including the contents of function.sh in the file at the point where the command is run.
You need to understand the difference between sourcing and executing a script.
Sourcing runs the script from the parent-shell in which the script is invoked; all the environment variables, functions are retained until the parent-shell is terminated (the terminal is closed, or the variables are reset or unset),
Execute forks a new shell from the parent shell and those variables,functions including your export variables are retained only in the sub-shell's environment and destroyed at the end of script termination.
Upvotes: 3
Reputation: 19982
When you source a file, the shebang in that file is ignored (it is not on the first line since it is included in the caller script and is seen as comment).
When you include an old script with #!/bin/sh
it will be handled as the shell of the caller. Most things written in /bin/sh
will work in bash
.
When you are running a sh or ksh script and you include (source
) a bash file, all bash specific code will give problems.
Upvotes: 1