0

In the script below, when the code inside the if statement is executed, the user gets logged out from bash. Why is this?

#!/bin/sh  
if [ -z $1 ]; then  
   echo "1"  
   read w  
   exit 1  
fi  
if [ "$#" -gt "1" ]; then
   echo "1"
  read w
  exit 2
fi
export PTSUSER=$1.
<some more code>
TwoStraws
  • 12,862
  • 3
  • 57
  • 71
  • The shebang `#!/bin/sh` makes this very much _not_ a Bash script. See also [Difference between `sh` and `bash`](https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash) – tripleee Mar 21 '22 at 06:36

3 Answers3

3

If the script is sourced, and either of the if blocks are hit, then yes the current users bash shell will be exited, and the user will be logged out. This is due to sourcing a script will use the current users bash shell to execute the script.

$ . ./script.sh

On the other hand if it's run in a new bash shell instance, then this won't happen, and the bash instance will exit once either of the exit commands are executed in the shell (in either of the if blocks).

$ bash ./script.sh
display101
  • 2,035
  • 1
  • 14
  • 10
1

It depends on how you call the script. exit causes the current shell to exit. If you source the script from a shell started after a login, i.e. it is run in the context of the current shell, exit will log the user out.

choroba
  • 231,213
  • 25
  • 204
  • 289
0

If you run the script using source and want to end script without logging-out the user,

Use return

Daniel Selvan
  • 959
  • 10
  • 23