0

Say I have a bash function:

run_stuff(){
   if is_in_script; then
      exit 1
   fi
   return 1;
}

basically, if I am running it in a script:

$ ./my-script.sh

then I want to exit with 1, but if I am running it directly in the terminal:

$ run_stuff

then I want to return 1 (o/w my terminal window will close)

what is the best way to check this cross-platform?

  • Possible duplicate of https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced – tripleee Jun 09 '19 at 08:04

2 Answers2

1

You can use $0.

echo $0 when run in my (bash) terminal returns -bash.

echo $0 in a script with no #! run with bash test.sh returns test.sh

echo $0 in a script with #!/bin/bash run as ./test.sh returns ./test.sh

mdszy
  • 93
  • 8
0

It's not bullet proof, but you can check whether the current shell is interactive:

is_in_script() {
  [[ $- == *i* ]]
}

However, I would just make run_stuff always return, and if a script should exit when the command reports failure, it can do run_stuff || exit rather than leaving this behavior up to the function itself.

that other guy
  • 116,971
  • 11
  • 170
  • 194