neel.1708
neel.1708

Reputation: 315

call main script function in script files called inside in shell script

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

Answers (3)

Mikhail Vladimirov
Mikhail Vladimirov

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

William Pursell
William Pursell

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

Majid Laissi
Majid Laissi

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

Related Questions