- The 25+ best Black Friday Nintendo Switch deals 2024
- Why there could be a new AI chatbot champ by the time you read this
- The 70+ best Black Friday TV deals 2024: Save up to $2,000
- This AI image generator that went viral for its realistic images gets a major upgrade
- One of the best cheap Android phones I've tested is not a Motorola or Samsung
How to log out of a Linux system from a script
If you run a script using a command like exec myscript and the script includes a logout command, the script will end abruptly and so will the shell from in which it was running.
Using the source builtin
Another way to log out of a system through a script is to use the source builtin to run the script. When you run a command such as source wait4three, the command will read and execute all the commands included in the script just as if you were typing them. In other words, the constraints involved in running a script are removed.
Another benefit of using the source builtin is that you don’t need execute permission to run a script, just read access.
One simple alternative
One very simple alternative to logging out from inside a script is to run both the script and the logout command on one line – separated by a semicolon. This ensures that the logout command will run once the script has finished.
$ wait4three; logout
The script shown earlier could then use exit instead of logout.
#!/bin/bash while true do sleep 10 count=`who | wc -l` echo $count if [ $count -ge 3 ]; then exit fi done
Wrap-up
While logging out of a system from a script is rarely required, there may be times when you need to run a lengthy process and want to be sure that you’re logged out when it completes. Running a script that includes the logout command and running with the exec or the source builtin makes this possible.