0

I have the below parent script which calls a child script.

parent.sh

#!/bin/bash
export home=`pwd`
echo "calling child"
. ${home}/bin/child.sh
retn_code=$?
if (retn_code -ne 0)
then
    exit $retn_code
else
    echo "successful"
fi
exit 0

child.sh:

#!/bin/bash
exit 1

When I execute the parent script, the exit status of 1 is not getting captured in parent script. The last line of the log printed is "calling child" and there are no lines printed after that in log.

Is there something I am missing while getting the exit status from child to parent?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Padfoot123
  • 1,057
  • 3
  • 24
  • 43

1 Answers1

2

. does not call the child, it runs its code. So if the child script calls exit, the parent exits. You want to do:

#!/bin/bash
home=$(pwd)
echo "calling child"
if "${home}"/bin/child.sh; then
    echo success
else
    exit   # status returned by child will propagate
fi
exit 0

Note that it's very odd to use the variable home here. If you want it defined in child.sh, IMO it would be clearer to write if home=$(pwd) ./bin/child.sh; then .... Your usage of export implies that you want it defined in child.sh, but I suspect you don't actually want that. It's not pertinent to the question, so I've just removed what I believe is an unnecessary export.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • This could/should have been marked duplicate of https://stackoverflow.com/questions/922651/unix-command-line-execute-with-dot-vs-without -- I was about to edit the duplicate list to add that when you reopened. – Charles Duffy Mar 11 '21 at 15:12
  • 2
    BTW, your `if` is backwards; it's currently `exit`ing in the success case, and echoing `successful` in the failure case. – Charles Duffy Mar 11 '21 at 15:13
  • ...whereas in the new version because the `!` is inverting `$?`, the `exit` no longer propagates the intended value. – Charles Duffy Mar 11 '21 at 15:13
  • @Biffen, `exit` uses `$?` by default, really. The trick (which early versions of this answer haven't gotten right) is to write the code so the child's exit status is still _in_ `$?` when the `exit` is reached. – Charles Duffy Mar 11 '21 at 15:13
  • @CharlesDuffy Reversed the logic to match the OP. Agree that this should be marked duplicate, but not sure of what. – William Pursell Mar 11 '21 at 15:14