Home > OS >  How can I write and reference global bash scripts which halt the parent script's execution upon
How can I write and reference global bash scripts which halt the parent script's execution upon

Time:08-25

I have written a simple script

get-consent-to-continue.sh

echo Would you like to continue [y/n]?

read response

if [ "${response}" != 'y' ];
then
  exit 1
fi

I have added this script to ~/.bashrc as an alias

~/.bashrc

alias getConsentToContinue="source ~/.../get-consent-to-continue.sh"

My goal is to be able to call this from another script

~/.../do-stuff.sh

#!/usr/bin/env bash

# do stuff

getConsentToContinue

# do other stuff IF given consent, ELSE stop execution without closing terminal

Goal

I want to be able to

bash ~/.../do-stuff.sh

And then, when getConsentToContinue is called, if I respond with anything != 'y', then do-stuff.sh stops running without closing the terminal window.

The Problem

When I run

bash ~/.../do-stuff.sh

the alias is not accessible.

When I run

source ~/.../do-stuff.sh

Then the whole terminal closes when I respond with 'n'.

I just want to cleanly reuse this getConsentToContinue script to short-circuit execution of whatever script happens to be calling it. It's just for personal use when automating repetitive tasks.

CodePudding user response:

A script can't force its parent script to exit, unless you source the script (since it's then executing in the same shell process).

Use an if statement to test how getConsentToContinue exited.

if ! getConsentToContinue
then
    exit 1
fi

or more compactly

getConsentToContinue || exit

CodePudding user response:

You could pass the PID of the calling script

For instance say you have a parent script called parent.sh:

# do stuff
echo "foo"

check_before_proceed $$ 

echo "bar"

Then, your check_before_proceed script would look like:

#!/bin/sh
echo Would you like to continue [y/n]?

read response

if [ "${response}" != 'y' ];then
  kill -9 $1 
fi

The $$ denotes the PID of the parent.sh script itself, you could find the relevant docs here. When we pass $$ as a parameter to the check_before_proceed script, then we would have access to the PID of the running parent.sh via the positional parameter$1 (see positional parameters)

Note: in my example, the check_before_proceed script would need to be accessible on $PATH

  •  Tags:  
  • bash
  • Related