What you're doing here is including second.sh
and third.sh
as sub-scripts running in the same process, which is called “sourcing” in shell programming. . ./second.sh
is basically equivalent to including the text of second.sh
at that point. The exit
command exits the process, it doesn't matter whether you call it in the original script or in a sourced script.
If all you want to do is run the commands in second.sh
and third.sh
and they don't need to access or modify variables and functions from the original script, call these scripts as child processes.
#! /bin/ksh
echo "prova"
./second.sh
echo "ho lanciato il secondo"
./third.sh
echo "ho lanciato il terzo"
If you need the other scripts to access variables and functions from the original script, but not modify them, then call these scripts in subshells. Subshells are separate processes, so exit
exits only them.
#! /bin/ksh
echo "prova"
(. ./second.sh)
echo "ho lanciato il secondo"
(. ./third.sh)
echo "ho lanciato il terzo"
If you need to use variables or functions defined in second.sh
and third.sh
in the parent script, then you'll need to keep sourcing them.
The return
builtin exits only the sourced script and not the whole process — that's one of the few differences between including another script with the .
command and including its text in the parent script. If the sourced scripts only call exit
at the toplevel, as opposed to inside functions, then you can change exit
into return
. You can do that without modifying the script by using an alias.
#! /bin/ksh
echo "prova"
alias exit=return
. ./second.sh
echo "ho lanciato il secondo"
. ./third.sh
unalias exit
echo "ho lanciato il terzo"
If exit
is also called inside functions, I don't think there's a non-cumbersome way. A cumbersome way is to set an exit trap and put your code there.
#!/bin/ksh
do_first () {
echo "prova"
trap "after_second" EXIT
. ./second.sh
after_second
}
after_second () {
echo "ho lanciato il secondo"
trap "after_third" EXIT
. ./third.sh
after_third
}
after_third () {
trap - EXIT
echo "ho lanciato il terzo"
}
do_first
.
command, which sources another file in the current shell. There is no child shell or subshell involved. Did you mean to executesecond.sh
andthird.sh
instead of sourcing them? – Celada Jul 22 at 15:25