Reputation: 315
I am still learning to write shell scripting so i don't know whether this can be done.
I have a main script called main.sh
Main.sh
#!/bin/bash
function log {
echo "[${USER}][`date`] - ${*}" >> ${LOG_FILE}
}
home/script/loadFile.sh && home/script/processData.sh
So my question is can i call my log function of main.sh inside loadFile.sh and processData.sh script file ? I tried it but i got error
line 1: log: command not found
Thanks.
Upvotes: 2
Views: 673
Reputation: 13890
When you start loadFile.sh
and processData.sh
like you do, they are started as ordinary executables, so parent shell does not recognize then as shell scripts and new instance of shell interpreter is started for each script. New shell interpreter does not know anything about your log
function.
When you run loadFile.sh
and processData.sh
like this:
. home/script/loadFile.sh && . home/script/processData.sh
Shell treats them as shell scripts rather than as ordinary executables and executes in current context, thus making function log
visible to them. Also, any functions/variables defined inside loadFile.sh
and processData.sh
will be visible in parent shell after they will exit, and thus these scripts has many ways to damange parent shell, which makes such way unsafe in some situations.
Upvotes: 1
Reputation: 212208
This is not portable, but in bash
you can simply export the function definition:
export -f log
home/script/loadFile.sh && home/script/processData.sh
Upvotes: 3
Reputation: 19778
you need to prompt like this:
. home/script/loadFile.sh && . home/script/processData.sh
But if you have an exit
command in your loadFile.sh or processData.sh then your main.sh will exist as well
Upvotes: 1