1

I have 2 shell scripts say a.sh and b.sh today, both are run standalone and have the exit code check like:

echo "Executing: $COMMAND"
eval $COMMAND
exitCode=$?
exit $exitCode

For a certain scenario I need to call b.sh from inside a.sh. I need to check if b.sh is getting called from a.sh then control should pass to a.sh after executing b.sh else follow the default behavior of b.sh

Is there any way in shell scripts I can get hold of the calling script? so that I can implement logic:

if ( calling script == a.sh)
then do not exit
else
  follow the default behavior
user1731553
  • 1,887
  • 5
  • 22
  • 33
  • Which shell are you using `bash` or other? – Inian May 08 '17 at 07:21
  • [Why should eval be avoided in Bash, and what should I use instead?](http://stackoverflow.com/questions/17529220/why-should-eval-be-avoided-in-bash-and-what-should-i-use-instead) – ceving May 08 '17 at 07:37

3 Answers3

1

you can track some variable in the file.

set VAR = A.SH //at the beginning of a.sh

and set it to other value in other place.

if you are using bash.you can get current file name by $0.

echo $0
Shihe Zhang
  • 2,641
  • 5
  • 36
  • 57
1

On Linux you can use the proc file system to get the command line arguments of some process. The parent process id of a shell script is stored in $PPID.

Assuming that a.sh looks like this:

#! /bin/bash
./b.sh

and you call it this way:

./a.sh

you can use the following b.sh to get the parent script name:

#! /bin/bash
cut -d $'\0' -f 2 /proc/$PPID/cmdline
ceving
  • 21,900
  • 13
  • 104
  • 178
0

You can ask for an arg to check the if statement in script b.sh. And the script a.sh executes the script b.sh with that exact arg.

Script a

sh ./b.sh script_a

Script b

if($1 == script_a) 
//$1 means first argument, which you typed in script a 
....
....
swizes
  • 101
  • 1
  • 9