Is it possible in sh
to define functions in one file and call them from another file and assign the result to a variable?
# pwd
/root
# ls
a.sh b.sh
# cat a.sh
the_function() {
echo "This is the function. It says: $1"
}
# cat b.sh
#!/bin/sh
/root/a.sh
the_function 'Called directly'
r=$(the_function 'hello')
echo "Result: $r"
# ./b.sh
./b.sh: 5: ./b.sh: the_function: not found
./b.sh: 7: ./b.sh: the_function: not found
Result:
Yes, you can import code from another file with .
(aka "source", though this alias is not available in POSIX sh
).
For your immediate question, the problem is the lack of the .
. Just running /root/a.sh
runs it in a subprocess, whose environment (including functions) will be lost as soon as that subprocess exits.
Here is a fixed b.sh
:
#!/bin/sh
. /root/a.sh
# notice the added dot
the_function 'Called directly'
r=$(the_function 'hello')
echo "Result: $r"
Unfortunately, the shell does not make it easy to build libraries of shared code; you need to know the directory which the code is saved in in order to be able to load it. This makes it hard to create properly modular reusable code in shell script.
A common arrangement for self-contained code distributed across multiple files is to have all your code in the same directory, and then do something like
#!/bin/sh
:
. "$(dirname "$0")"/shared.sh
the_function "sourced from shared.sh"