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?

1

2 Answers 2

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

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

Comments

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.

Comments

Your Answer

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