2

I have a script like this:

#/bin/bash

check(){

  if [ "$1" == "" ];then
    exit 1
  fi
  echo "return value"
}

echo "Before"
var=$(check $1)
echo "After"

I expect that when no argument is passed into check(), the program will exit, and therefore "After" will not be printed out.

However, the code "exit 1" only exits the function rather that the program when the return value is assigned to a variable "var".

Does anyone know how to achieve this?

Thanks in advance.

gn01842919
  • 21
  • 1
  • 1
    `$()` will execute the command in a subshell. You are exiting that shell with `exit`. There is no way of exiting multiple levels of shell at once. – RedX Oct 06 '16 at 08:00
  • You could commit suicide: Pass the PID of the shell you want to exit to the function, and use `kill`. If you want to die more gracefully, you could (maybe: should) `trap` the signal in the shell to be killed and do the necessary cleanup before exiting. – user1934428 Oct 06 '16 at 08:02

0 Answers0