3

How do I get the exit code from my subscript in main script. In my script below when the subscript fails it exits from the main script as well.

#!/bin/bash
function reportError() {
    if [ $1 -ne 0 ]; then
        echo $2
        exit $1
    fi
 }

 #executing the subscript

 /data/utility/testFolder.sh
 #calling the function if there is any error then function would update the 
 #audit table
 reportError $? "job is failed, please check the log for details"

Subscript code -

#!/bin/bash

if [ -d "/data/myfolder/testfolder" ]
then
  echo "ERROR: Directory does not exists"
  exit 1   
else
    echo "INFO: Directory exists"
    exit 0
fi
9
  • Huh? Nothing in here is changing your current working directory at all. Commented Sep 13, 2017 at 18:11
  • 2
    BTW, you've got a whole bunch of quoting bugs. Consider fixing everything identified by shellcheck.net before asking questions here. Commented Sep 13, 2017 at 18:12
  • 2
    ...back to trying to identify a problem, though -- please build a minimal reproducible example: The shortest possible code someone else can run without modification or external dependencies to see your problem themselves. Commented Sep 13, 2017 at 18:12
  • I have updated the question ,description and code to give more clarity what I need.... regret for the original post which was not clear...
    – AJ007
    Commented Sep 13, 2017 at 19:13
  • I could not load an example in shellcheck.net
    – ideaboxer
    Commented Sep 13, 2017 at 19:36

1 Answer 1

1

I checked your code and everything is fine except you made a mistake in the subscript condition.

#!/bin/bash
function reportError() {
    if [ $1 -ne 0 ]; then
        echo $2
        exit $1
    fi
 }

 #executing the subscript

 /data/utility/testFolder.sh
 #calling the function if there is any error then function would update the 
 #audit table
 reportError $? "job is failed, please check the log for details"

Child script:

#!/bin/bash

if [ ! -d "/data/myfolder/testfolder" ] # add "!". More details: man test
then
    echo "ERROR: Directory does not exists"
    exit 1   
else
    echo "INFO: Directory exists"
    exit 0
fi
2
  • "Subscript" isn't a very well-defined term, and it's close to something that would be misleading: "subshell" implies a fork without an exec (thus, a copy of the original shell with all local variables intact), but we are having an exec() call. It's safer just to call it the "child script" or "child process". Commented Sep 13, 2017 at 19:47
  • 1
    @CharlesDuffy, thanks! I just tried to express the answer in the author's terminology.
    – RedEyed
    Commented Sep 13, 2017 at 19:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.