0

I have a few scripts:

functions.sh - has many functions defined including work() and abort() it looks like this:

#!/bin/bash

abort()
{
message=$1
echo  Error: $message ..Aborting >log
exit 7
}

work()
{
cp ./testfile ./test1           #./testfile doesnt exist so non zero status here

if [ $? -eq 0 ];then
        echo "variable_value"
else
        abort "Can not copy"
fi
}

parent.sh - parent script is the main script, it looks like this:

#!/bin/sh

. ./functions.sh

value=$(work)
echo "why is this still getting printed"

Basically i have many functions in the functions.sh file, and i am sourcing that file in parent.sh to make available all functions. Parent can call any function and any function in functions.sh can call abort at which point execution of parent should stop, but its not happening, parent.sh runs to the next step. Is there a way to get around this problem?

I realise that its happening due to assignment step value=$(work). But is there a way to abort execution just at abort function call in this case?

n joshi
  • 1
  • 2
  • 1
    I'm unable to reproduce this: 1. I pasted the first section into a file called `functions.sh`. 2. I pasted the second section into `parent.sh`. 3. `chmod +x parent.sh && ./parent.sh`. The output I got was `./functions.sh: line 10: do_something: command not found` followed by `Problem: Looks like a failure`. I did *not* see the "This step should not run" message. Can you please try again? Remember to always test the code you post, since any edits you make between testing and posting can hide the problem. – that other guy Feb 11 '19 at 18:07
  • Your shell might be trapping 7 somehow? You can test this by simply invoking `work` in your interactive shell. It should abort the entire shell and (on many platforms) close your shell window. –  Feb 11 '19 at 18:08
  • Thank you for your comments, i realised i changed the code and it was not reproducing my problem. I have edited my question and code now, can you please look at this again? – n joshi Feb 11 '19 at 20:02

1 Answers1

0

I'm not convinced that this behavior should be described as a "problem". As you noted, when you invoke work in a subshell, aborting from work just aborts the subshell. This is correct, expected behavior. Fortunately, the value returned by work in the subshell is available to the parent, so you can simply respond to it and write:

value=$(work) || exit

If work returns a non-zero value, then the script will exit with that same non-zero value.

William Pursell
  • 204,365
  • 48
  • 270
  • 300