Switch Between CLI and GUI on Linux

Switch Between CLI and GUI on Linux

In the Linux systems, users has flexibility to choose between command-line interface (CLI) and graphical user interface (GUI) environments based on their preferences or system requirements. This flexibility is particularly useful for system administrators and developers engaged in tasks ranging from fine-tuning server configurations to optimizing their development environment. This tutorial explains how to switch between CLI and GUI on Linux.

The commands presented in the post are applicable for Linux distributions based on systemd such as Ubuntu, Debian, and others.

Before delving into the commands for switching between CLI and GUI on Linux, it's crucial to understand the concept of targets. In the systemd, boot choices are encapsulated as targets, representing different system states during the boot process. Two primary targets are particularly relevant to our scenario: multi-user.target, denoting the CLI, and graphical.target, representing the GUI.

Get current target

To begin, let's understand how to check the current default target. Use the following command:

sudo systemctl get-default

This command shows whether the system is currently set to boot into the GUI or CLI by displaying either graphical.target or multi-user.target.

Enable CLI on boot

If you want the system to boot into CLI mode by default, execute the following command:

sudo systemctl set-default multi-user.target

This command sets the default target to multi-user.target, ensuring the system boots into the CLI on the next restart.

Enable GUI on boot

Conversely, if a graphical environment is more suitable, use the following command:

sudo systemctl set-default graphical.target

Executing this command sets the default target to graphical.target, prompting the system to boot into the GUI on the next restart.

Bash script

To implement the transition between CLI and GUI effectively, you can use the following Bash script:

#!/bin/bash

if [[ ! $1 =~ ^(1|0)$ ]]; then
  echo 'Available arguments: 1, 0'
  exit 1
fi

if [[ $1 == 1 ]]; then
  sudo systemctl set-default graphical.target
else
  sudo systemctl set-default multi-user.target
fi

echo 'Reboot system required'

This script takes a single argument (1 or 0), where 1 sets the default target to graphical.target (GUI), and 0 sets it to multi-user.target (CLI). After executing the script, remember that a system reboot is necessary for the changes to take effect.

Save script in a file, for instance, gui. After creating the script, make it executable. You can use the following command to add execute permission:

chmod a+x gui

After applying this command, you can execute the script using:

./gui 0
./gui 1

Leave a Comment

Cancel reply

Your email address will not be published.