0

basically I have written a shell script for a homework assignment that works fine however I am having issues with exiting. Essentially the script reads numbers from the user until it reads a negative number and then does some output. I have the script set to exit and output an error code when it receives anything but a number and that's where the issue is.

The code is as follows:

if test $number -eq $number >dev/null 2>&1
then
   "do stuff"
else
    echo "There was an error"
    exit

The problem is that we have to turn in our programs as text files using script and whenever I try to script my program and test the error cases it exits out of script as well. Is there a better way to do this? The script is being run with the following command in the terminal

script "insert name of program here"

Thanks

8
  • How do you run your script? Commented Nov 30, 2015 at 22:47
  • Possible duplicate of stackoverflow.com/questions/6112540/… Commented Nov 30, 2015 at 22:50
  • @JerryJeremiah, given as the OP doesn't seem to know whether they're invoking or sourcing at all, I'm not sure this can be a duplicate until they're informed enough to pick one. :) Commented Nov 30, 2015 at 22:51
  • Aside: See shellcheck.net to get the easy-to-catch bugs detected automatically before you ask questions here. Commented Nov 30, 2015 at 22:52
  • Also, your script "insert name of program here" isn't very helpful. Is script in this case the external script command? Is it the outer test script, where insert name of program here is the name of the inner script under test? If so, how is the test script invoking the program under test? Commented Nov 30, 2015 at 22:57

1 Answer 1

1

If the program you're testing is invoked as a subprocess, then any exit command will only exit the command itself. The fact that you're seeing contrary behavior means you must be invoking it differently.


When invoking your script from the parent testing program, use:

# this runs "yourscript" as its own, external process.
./yourscript

...to invoke it as a subprocess, not

# this is POSIX-compliant syntax to run the commands in "yourscript" in the current shell.
. yourscript

...or...

# this is bash-extended syntax to run the commands in "yourscript" in the current shell.
source yourscript

...as either of the latter will run all the commands -- including exit -- inside your current shell, modifying its state or, in the case of exit, exec or similar, telling it to cease execution.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.