Reputation: 6309
Here are my script files:-
# Log stdout and stderr
log_stdout_and_stderr() {
# Close STDOUT file descriptor
exec 1<&-
# Close STDERR FD
exec 2<&-
# Open STDOUT as $1 file for read and write.
exec 1<>$1
# Redirect STDERR to STDOUT
exec 2>&1
}
Log a single line
log() {
echo "[$(date)]: $*"
}
log_stdout_and_stderr main.log
log "Started main.sh"
log "Completed main.sh"
# call first_script
source first_script.sh
log_stdout_and_stderr first_script.log
log "Started first_script.sh"
# call second_script
source second_script.sh
log "Completed first_script.sh"
log_stdout_and_stderr second_script.log
log "Started second_script.sh"
log "Completed second_script.sh"
Below are my outputs logs:-
Started main.sh
Completed main.sh
Started first_script.sh
Started second_script.sh
Completed second_script.sh
Completed first_script.sh
I want to log messages should be logged like below in the log files.
Expected output:-
Started main.sh
Completed main.sh
Started first_script.sh
Completed first_script.sh
Started second_script.sh
Completed second_script.sh
I am calling second_script.sh file from first_script.sh. I want to store the log messages used by second_script.sh in second_script.log
How can I do it? Let me know if anyone is not clear about the question.
Upvotes: 2
Views: 213
Reputation: 1562
You are using source
in order to call the scripts from the main
script.
Sourcing a script means that it is parsed and executed by the current shell itself. It's as if you typed the contents of the script within the main
script. i.e.:
The following is an equivalent when you call the second_script.sh
within the first_script.sh
:
first_script.sh
log_stdout_and_stderr first_script.log
log "Started first_script.sh"
# call second_script
####### second_script.sh called with sourcing #######
log_stdout_and_stderr second_script.log
log "Started second_script.sh"
log "Completed second_script.sh"
######################################################
log "Completed first_script.sh"
Since the script will be executed sequentially, logs will be stored according to the last called log_stdout_and_stderr
.
In order to avoid this:
first_script.sh
to:log_stdout_and_stderr first_script.log log "Started first_script.sh" #call second_script source second_script.sh log_stdout_and_stderr first_script.log log "Completed first_script.sh"
log_stdout_and_stderr first_script.log log "Started first_script.sh" # call second_script /path/to/second_script.sh log "Completed first_script.sh"
This way you'll call another bash shell to execute the other script (in this case second_script.sh
). Calling the script this way you'll need to add execution permissions to the script you're calling.
Upvotes: 1