1

For example, A.sh calls B.sh inside the source code. The call is as the following in A.sh

#Inside A.sh    
. ./B.sh

Now, some if..else statement happened in B.sh and decided to stop executing B.sh. How to make it go back to A.sh and keep executing the rest of the codes?

Thanks.

return 0
  • 4,226
  • 6
  • 47
  • 72

3 Answers3

1

The . basically means run this file in the current shell. That means that any exit or similar will exit the current (A) shell.

You need to make sure B is done in a different shell.

I haven't tested it, but ( . ./B.sh ) might work...

As others have stated, you can simplify event more: ./B.sh is also likely to work.

John3136
  • 28,809
  • 4
  • 51
  • 69
  • `.` is usually used because you _need_ to run the script in the same shell, so this is not likely to be a useful answer. The duplicate question I linked to has an answer that works. – Barmar Oct 24 '13 at 00:27
1

You've probably noticed that if you call exit from a file that's being sourced, you exit the entire shell, not just that file.

Instead, you can use return, which (in addition to returning from a function) will return control to the command following the . command.

Note that it is an error to return from a script that is being executed, rather than sourced, so make sure that you only use return outside of a function in a file that will be sourced.

chepner
  • 497,756
  • 71
  • 530
  • 681
-1

foo.sh:

#!/bin/bash

echo "hi"
./bar.sh
echo "done"

bar.sh:

#!/bin/bash

echo "bar here!"
[[ "1" == "1" ]] && exit 0
echo "oh no!"

Run foo.sh:

$ ./foo.sh
hi
bar here!
done
kevinsa5
  • 3,301
  • 2
  • 25
  • 28
  • You're ignoring the requirement that `B.sh` is being sourced, not executed as a script. There are legitimate and necessary reasons for doing so; executing as a script so that you can use `exit` may not be possible. – chepner Oct 24 '13 at 12:38
  • @chepner Ah, good call. Thanks for the correction. – kevinsa5 Oct 24 '13 at 14:28