Shutdown linux ubuntu server

How to Shut Down Ubuntu

Ubuntu was initially a terminal-based operating system, but over time Linux slowly introduced the GUI in its operating system. Nowadays, GUI methods are the only way to solve many operating system problems. Well, we are here to teach you some cool methods that can help you shut down your system in Ubuntu like a pro!

Ubuntu, like all other operating systems, offers several ways to shut down, and these include such simple methods as clicking a button and also giving commands to the system via a terminal.

Shutdown Ubuntu using System menu

If you are using an Ubuntu Desktop, then it’s easy to shut down or poweroff the system. Ubuntu’s system menu provides the option of a power-off button in a drop-down menu, in the top right corner of the desktop. By clicking the power button, a dialogue box with 3 options will appear.

  • Cancel
  • Restart
  • Power off

You will be able to make a choice in 60 seconds after 60 seconds system will shut down automatically.

Shutdown Ubuntu by using the Terminal

The following instructions will use the command line, so you can use them on Ubuntu server- and desktop systems and headless installations like cloud servers. On the desktop, Terminal can be opened by simply pressing Alt + Ctrl +T keys on the keyboard or by a right-click on the desktop and click open terminal. For servers and headless systems, you probably use an SSH client to get a terminal connection. Several commands are used for shutting down the system.

Power off and poweroff command

This command immediately shuts down the system.

This command asks for a password and then shut down the system.

Shutdown -h now

This command will immediately shut down the system.

Schedule Ubuntu Shutdown

But if you want to shut down the system after a certain time you can specify time instead of ‘now’. It will shut down the system after the specified time. For this type command:

This command will shut down the system after 1 minute.

To cancel this shutdown command, type command:

An alternate command for shutting down the system after a specified time is:

This will shut down the system after 30 minutes.

You can also leave a comment with shut down command. Type command

Shutdown Ubuntu at a Specified Time

If you want to shut down at a specified time like 8:03 pm type command:

Get a list of shutdown parameters

To get a list of all the parameters that can be used with shutdown command along with their uses type command:

The shutdown command can do a lot with the following parameters.

Get a list of all Power Off command parameters

The poweroff command can also be used with different parameters. To get a list of all the parameters that can be used with poweroff command along with their uses type command:

So you got to know that there are so many ways to shut down and power off your machine in Ubuntu. The basic commands of shutdown and poweroff with different parameters can perform a variety of functions to halt a session. You can now use any of the above-mentioned ways to power off your machine.

Читайте также:  Broadcom serial bus driver over uart bus enumerator windows 10

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

5 Linux Commands to Shutdown and Reboot the System

Linux shutdown / reboot command

On Linux, like all tasks, the shutdown and restart operations can also be done from the command line.

The commands are shutdown, halt, poweroff, reboot and REISUB keystrokes.

In this post I am going to show you how to shutdown or restart a linux system using these commands.

The commands are useful specially when you have to reboot a remote linux server, where only shell access is available and no gui.

Servers often need a restart when upgrades are installed or need to shutdown for other maintainance tasks.

The commands are available on any linux system like centos, ubuntu, debian, fedora or suse and do not require the installation of any extra packages.

1. «shutdown» command

The first command is the shutdown command and it can be used to shutdown a system or restart it. It is commonly used to shutdown or reboot both local and remote machines.

To shutdown a machine call the shutdown command like this

The h option is for halt which means to stop. The second parameter is the time parameter. «now» means that shutdown the system right away.

The time parameter can be specified in minutes or hours also. For example

The above command shall flash the message to all other logged in users and give them 5 minutes before the system goes for shutdown.

The shutdown command can be used to restart a system with the r option instead of the h option. Usage is same as before. Just replace the h option with r option.

All other logged in users will see a broadcast message in their terminal like this

At this point a shutdown can be cancelled by calling shutdown with «c» option.

2. «reboot» command

Next command is the reboot command. It can be used to shutdown or reboot linux.

The following command will shutdown linux.

The «p» options stands for poweroff.

To reboot linux just call the reboot command directly without any options.

This will perform a graceful shutdown and restart of the machine. This is what happens when you click restart from your menu.

Reboot linux forcibly

The following command will forcefully reboot the machine. This is similar to pressing the power button of the CPU. No shutdown takes place. The system will reset instantly.

The man page explains it as follows

3. «halt» command

The next command is the halt command. This can shutdown a system

The halt command also has a force option, but you do not want to use it. It is supposed to shutdown the system instantly. But its behaviour may not be consistent. Desktops might hang on running this command.

4. «poweroff» command

There is another command exactly same as the halt command. It does the same things and takes the same options.

5. REISUB — R E I S U B key strokes

The above shown commands can be used when you are in control of your system. What if the system has hanged and is not responding at all. And you do not want to press the power button on the CPU which might lead to data corruption. To save from such a situation, comes the magic sysRQ keys.

Читайте также:  Windows грузится только безопасный режим

A special combination of key presses that will allow you to reboot your linux system, no matter how much it is hanged. Check the wikipedia article. for more information.

Warning : Pressing the following keys would instantly reboot your system. Its similar to pressing the power button of your CPU or executing the reboot -f command.

Now in place of the B key we have to use R E I S U letters first. Each key does a task as mentioned below

1. Hold down the Alt and SysRq (Print Screen) keys.
2. While holding those down, type the following keys in order, several seconds apart: R E I S U B
3. Computer should reboot.

Make sure to have some time gap between each of keys R E I S U B.

The sysrq feature can be controlled by changing the value of /proc/sys/kernel/sysrq. To check if sysrq is enabled on the system or not, echo the value. It should be non zero.

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

10 thoughts on “ 5 Linux Commands to Shutdown and Reboot the System ”

It worked on SUSE SLES 11

Now systemctl utility replaces a number of power management commands and even the shutdown command will call systemctl utility to perform the shutdown tasks.

The command reboot does work and immediately rebooted my Bluestar Linux system 4.20.7 (based on Arch Linux).

I am so glad that you could reboot your linux system!

If I’m not mistaken, reboot by itself actually does a shutdown: https://linux.die.net/man/8/reboot . You have to do reboot -f to actually get it to reboot.

Arrrgh so sick of finding the incorrect example of shutdown everywhere. The reboot syntax shown, on Ubuntu and probably in every flavor today, will Immediately reboot your server with no delay or warning. the +5 option is either wrong or in the wrong spot.

Important note – this only applies (AFAIKT) to x86 systems. On arm – no-worky.

what? 20 – 30 mins? O.o Shouldn’t it be 20 – 30 seconds?

I rebooted my linux machine using command reboot -f, it went down. How long does it takes normally to start again?

Its depends upon hardware and file system mounted on Linux box , If it is high end hardware and have been mounted more file system then it will 20-30 mins to come online

Источник

linux

ВЫКЛЮЧЕНИЕ LINUX ИЗ КОМАНДНОЙ СТРОКИ

  • Получить ссылку
  • Facebook
  • Twitter
  • Pinterest
  • Электронная почта
  • Другие приложения

Выключение компьютера — действие, с которым обычные пользователи сталкиваются чуть ли не каждый день. Если выключать сервер приходится довольно редко, то обычные, десктопные компьютеры подвержены этой операции очень даже часто. Большинство пользователей выключают linux в графическом интерфейсе системы. В окружении рабочего стола KDE это делается через главное меню, а в Gnome и Unity даже есть специальная кнопка на панели для решения этой задачи.

Но не всегда есть возможность выключить компьютер linux таким образом. Например, если окружение рабочего стола не работает, то больше ничего не остается, кроме того, чтобы выполнять выключение компьютера из командной строки. К тому же выключение компьютера linux через терминал единственно возможный способ для серверов, где нет графического интерфейса. Как вы увидите, этот способ также намного гибче обычного выключения, поскольку вы можете настроить нужное время отключения, или же выключить компьютер, дождавшись завершения работы определенной программы.

Чтобы выключить компьютер Linux используется команда shutdown. Есть также команды poweroff, halt, но они для нестандартных случаев. Обычно же хватает одной только shutdown. Также выключить linux из консоли можно с помощью сочетаний клавиш SysRq. Но сначала давайте рассмотрим синтаксис команды shutdown.

Читайте также:  Обычный запуск windows кнопка

СИНТАКСИС SHUTDOWN

Синтаксис команды очень простой:

$ shutdown [опции] [время] [сообщение]

Опции задают параметры отключения, их мы рассмотрим ниже. Время можно задавать в формате чч:мм в 24 часовом формате. Также можно использовать запись +минуты, указывающую через сколько минут от текущего момента нужно выключить компьютер linux. Также доступна константа now, указывающая, что выключать нужно прямо сейчас.

Параметр сообщение позволяет задать сообщение, которое будет выведено в терминал перед выключением.

ПРОЦЕСС ВЫКЛЮЧЕНИЯ LINUX

Естественно, команда shutdown linux или любая другая не самостоятельно завершает работу системы и выключает компьютер. Она всего лишь передает запрос на выключение системе инициализации, а затем ядру. А уже они выполняют ряд сложных операций по подготовке и выключению компьютера. Если кратко, то вот они:
Завершение процессов пользователя
Сигнал SIGTERM всем процессам
Сигнал SIGKILL всем процессам
Монтирование файловых систем в режиме только для чтения
Подготовка внешних устройств к отключению
Блокировка пространства пользователя, чтобы гарантировать, что ни один код пользователя больше не будет запущен
Завершение работы и отключение питания большинства периферических устройств
Отключение питания компьютера

Теперь вы понимаете суть процесса выключения и то почему нельзя просто выдернуть шнур питания с розетки. Если это сделать, компьютер отключится моментально и не выполнит всех необходимых операций, а это может грозить потерей не сохраненных или даже недавно сохраненных данных, повреждением файловой системы и т д. Поэтому желательно выключать компьютер правильно с помощью shutdown или других специальных утилит.

А теперь перейдем к примерам.

ВЫКЛЮЧЕНИЕ КОМПЬЮТЕРА В LINUX

1. SHUTDOWN

Самая простая и самая часто используемая команда выключения компьютера linux, отключит компьютер немедленно:

sudo shutdown -h now

Как видите, используется обычное выключение, и константа времени now, тоесть сейчас.

Теперь попробуем запланировать выключение компьютера linux через пять минут:

sudo shutdown -h +5 «Компьютер будет выключен через 5 минут»

Мы запланировали вывод сообщения перед выключением.

Теперь давайте отменим выключение компьютера Linux:

sudo shutdown -c

Точно так же мы можем указать точное время выключения, например в девять вечера:

sudo shutdown -h 21:00

Как я уже говорил, не только команда shutdown linux умеет выключать компьютер, есть еще несколько утилит способных на это. Рассмотрим их тоже.

2. REBOOT

Команда reboot обычно используется для перезагрузки системы, но она также умеет выключать компьютер. Мы не будем ее подробно рассматривать, потому, что она еще проще команды shutdown. Для выключения нужно задать опцию -p:

3. HALT

Эта команда тоже выключает компьютер. Только делает она это очень по-своему. Она не выполняет никаких подготовительных действий перед выключением, а просто отключает питание:

Использование halt может повредить систему

4. POWEROFF

Это аналог halt, делает в точности то же самое:

5. SYSRQ

Помните, в начале статьи, я говорил о сочетании клавиш для включения компьютера? Рассмотрим этот вопрос подробнее.

SysRq — это подсистема, реализованная на уровне ядра. Ядро обрабатывает все нажатия клавиш, а с помощью этой подсистемы, оно может принимать от пользователя команды, даже когда система полностью зависла. Основное предназначение этой подсистемы — работа с компьютером в проблемных ситуациях, например, если вы думаете что ваш компьютер заразил вирус, или компьютер завис и его нужно выключить. Для доступа к SysRq используются сочетания клавиш Alt+PrtScr+номер

Самое интересное, что мы можем выполнить безопасное выключение компьютера linux. Для этого зажмите клавиши Alt + PrtScr и поочередно нажимайте:

  • R — разблокировать клавиатуру
  • E — послать всем процессам сигнал SIGTERM
  • I — послать всем процессам сигнал SIGKILL
  • S — перенести все данные из кеша файловых систем на диск
  • U — перемонтировать файловые системы только для чтения
  • B — перезагрузить

Также вместо всего этого можно воспользоваться сочетанием клавиш Alt+PrtScr+O, в таком случае, вся процедура будет выполнена автоматически, эта команда поддерживается не всеми ядрами.

Источник

Оцените статью