want user will logout from shell on exit of bash script
Solution 1
Instead of starting the script normally, exec
it instead. This will replace the login shell, so when the script finishes the user will be logged out.
Solution 2
End your script with kill -HUP $PPID
$PPID is the process ID of the parent process.
Solution 3
Depending on what you are trying to accomplish, you could use the script name instead of the shell in /etc/passwd.
The last entry in /etc/passwd (everything after the last colon) is the shell that is run when the user logs on. By changing this to the name of your script, when the script ends, then by definition, so does the shell.
** Be very careful editing /etc/passwd however, as you could lock yourself out of your machine. Apparently you can do this with
usermod --shell <script name> <user name>
which would be the safer way to make this change.
Solution 4
Another approach may be to source
the script instead of calling it directly, an exit
statement in the script will then close the user shell:
$ cat exit_me.sh
#!/bin/bash
exit
and
$ source exit_me.sh
# or
$ . exit_me.sh
More info about source
here.
Related videos on Youtube
Lucas Kauffman
I'm a Belgian security consultant living in Singapore, I'm here to learn and help others out. Opinions are my own. Advice provided with no warranty. Find me on http://cloud101.eu Sometimes you can have a craving only hands can satisfy!
Updated on September 17, 2022Comments
-
Lucas Kauffman over 1 year
I want, when a linux user exits from a shell script, that it also logs out from the bash shell. Is this possible?
-
Julien Vehent over 13 yearsthe exit will exit the current bash script, and not the bash of the user running it
-
user188129 over 13 yearsno exit will terminate only that script not the bash shell
-
FooBee over 13 yearsThis will just exit the sub-shell where the script is executed and doesn't solve the question.
-
FooBee over 13 yearsThere is a variable for that: $PPID
-
iSee over 13 years
$PPID
might fail if the script is run from a subshell, e.g. bash login shell → another bash shell → this script. Also why-9
and not-HUP
? -
Dennis Williamson over 13 yearsYes, definitely use
$PPID
. Usingps
in that way will log the user out of other sessions, too, which may be very undesirable. -
Julien Vehent over 13 yearskill -9 closes all processes it can without letting them close their file descriptors, freeing their memory, etc... I don't think it's a good idea if the script does any I/O.
-
FooBee over 13 yearsYes, you are right. Feeling a little bit destructive today ;)