- 5 Linux Commands to Shutdown and Reboot the System
- Linux shutdown / reboot command
- 1. «shutdown» command
- 2. «reboot» command
- 3. «halt» command
- 4. «poweroff» command
- 5. REISUB — R E I S U B key strokes
- 10 thoughts on “ 5 Linux Commands to Shutdown and Reboot the System ”
- 5 способов выключить компьютер с Linux через терминал
- 1. Отключение
- Перезапустить с -r
- 2. Перезагрузка
- 3. Остановить
- 4. Poweroff
- 5. Аварийный вариант: REISUB
- Помогите, я случайно выключил свой Linux компьютер или сервер!
- How to use Linux Shutdown Command with Examples
- shutdown Command Syntax
- How to Use the shutdown Command
- Shutdown With All Parameters
- How to Shut Down the System at a Specific Time
- How to Shut Down the System Immediately
- How to Broadcast a Custom Message
- How to Cancel a Scheduled Shutdown
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.
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
Источник
5 способов выключить компьютер с Linux через терминал
Ни одна операционная система не идеальна. Даже если это так, могут быть проблемы с драйверами и приложениями. Linux не является исключением. Несмотря на то, что он более стабилен, чем Windows, вероятно, придет время, когда вам нужно перезагрузить компьютер с Linux.
Но как ты мог это сделать? Доступны несколько команд для выключения или перезагрузки компьютера Linux через терминал.
Давайте посмотрим на них по очереди и рассмотрим, как и когда следует использовать эти команды.
1. Отключение
Если вы закончили работу с Linux, решение просто отключить его, для это можно использовать синтаксис команды:
shutdown [option] [time] [message]
Например, чтобы немедленно выключить компьютер, вы должны использовать:
Где -h означает остановку, а now – сейчас, что означает, инструкция должна быть выполнена немедленно. Различные задержки могут быть использованы. Например, вместо этого вы можете использовать +5, что скажет компьютеру выполнить процедуру выключения через пять минут.
Если вы хотите использовать message (сообщение), оно будет мигать всем зарегистрированным пользователям:
shutdown -h +5 «Сервер выключается, сохраните свою работу и выйдите из системы.»
Помните, что вы можете найти полный список переключателей для этих команд, введя:
Перезапустить с -r
Альтернативный вариант – использовать команду -r для перезагрузки компьютера. Она используется вместо -h, поэтому, для перезагрузки компьютера или сервера вы можете использовать:
shutdown -r +5 «Сервер перезагружается через пять минут, сохраните свою работу и выйдите из системы.»
Любое запланированное отключение или перезапуск можно отменить, введя команду -c:
2. Перезагрузка
Поскольку команда shutdown имеет опцию перезапуска, неудивительно, что команда reboot имеет опцию shutdown.
Стандартная команда перезагрузки:
Это предложит вашему компьютеру выключиться и снова включиться. Однако, если вы хотите выключить устройство, то ключ -p будет работать:
Другой вариант – принудительная перезагрузка. Это может быть полезно, если приложение или служба зависли и вам нужно быстро перезагрузиться:
Эта команда принудительно перезагрузит ваш Linux ПК.
3. Остановить
Мы уже видели переключатель -h выше, но остановка может использоваться как команда сама по себе. Это приведет к немедленному отключению компьютера с помощью простого четырехбуквенного слова:
Переключатель -f также можно использовать с остановкой, но результаты противоречивы, и может привести к проблемам стабильности системы.
4. Poweroff
Вы можете предпочесть терминологию команды poweroff. Это делает то же самое, что и halt, за исключением того, что ввод текста занимает в два раза больше времени.
Однако, кроме использования -f для принудительного отключения питания, вы также можете использовать ключ -w для регистрации вызова перезагрузки системы в /var/log/wtmp. Это потенциально полезный инструмент отладки, как -verbose, который может помочь с проблемами при завершении работы.
5. Аварийный вариант: REISUB
Все вышеперечисленные команды можно использовать в ситуациях, когда система работает без проблем. Но что делать, если компьютер или сервер зависает и не может быть перезагружен приемлемым способом?
Ответ тогда – комбинация клавиатуры. Если вы переключились с Windows, вы, вероятно, знаете, что Ctrl + Alt + Del отображает меню с выключением в качестве опции. Если удерживать дольше, машина выключится автоматически. В то же время на Mac вы просто должны удерживать кнопку питания (опция, которая также работает на оборудовании Windows).
В Linux комбинация клавиш для перезагрузки Alt + Print Screen + B. Однако, если это не работает или существует более сложная проблема, вы можете изменить комбинацию, используя до шести клавиш.
Это известно как REISUB, из-за следующей вынужденной аббревиатуры:
- unRaw – возвращает управление клавиатурой обратно с сервера X-дисплея.
- tErminate – посылает сигнал завершения SIGTERM всем процессам для корректного завершения.
- kIll – как и выше, но сигнал SIGKILL, который вызывает немедленное завершение процессов.
- Sync – сбрасывает данные на диск.
- Unmount – перемонтирует все файловые системы в состояние только для чтения.
- reBoot – что и следовало ожидать.
Чтобы это сработало, вы должны удерживать Alt + Print Screen, а затем, поочерёдно нажимать клавиши: R E I S U B, в этом же порядке. Задержка между каждым нажатием должна составлять 1-2 секунды. Это необходимо для того, чтобы дать немного времени на выполнение всех вышеперечисленных процессов. Обратите внимание, что этот метод обычно не работает на компьютерах с архитектурой ARM.
Помогите, я случайно выключил свой Linux компьютер или сервер!
Мы видели, как отменить команду выключения или перезапуска. Однако бывают ситуации, что вы запускаете команду выключения, когда выполняется жизненно важный процесс, особенно на удаленном сервере. Обойти это можно, установив molly-guard, который может отменить отключение, проверив определенные параметры.
Например, есть скрипт, который проверяет наличие сессий SSH. Если вы отправите команду перезагрузки, остановки или выключения molly-guard потребует имя хоста, который вы собираетесь закрыть.
Для этого установите molly-guard в терминал:
sudo apt-get install molly-guard
Поскольку molly-guard работает в фоновом режиме, он обнаружит такую команду, как poweroff, и сообщит, что был обнаружен сеанс SSH. Затем вы можете ввести имя хоста сервера для подтверждения выключения или нажать Ctrl + C для отмены. Полезно!
Эти пять способов выключения компьютера Linux из командной строки особенно полезны, поскольку их можно использовать на самом компьютере или через удаленный SSH. Поскольку эти команды очень лаконичны, они пригодны для быстрого использования – что может привести к случайной перезагрузке время от времени! К счастью, утилиты molly-guard достаточно, чтобы этого избежать.
Чтобы узнать больше о командах Linux, ознакомьтесь с нашей справочной таблицей.
Источник
How to use Linux Shutdown Command with Examples
Home » SysAdmin » How to use Linux Shutdown Command with Examples
All Linux users and system administrators need to know how to shut down the entire system safely. There are several options to do so, including scheduling a shutdown at a specific time, shutting down immediately, broadcasting a unique message, and so on.
In this tutorial, learn how to use the Linux shutdown command with examples.
shutdown Command Syntax
Before going into specific ways to shut down your Linux system, you should understand the basic syntax of the shutdown command:
- [options] define whether you want to halt, power-off, or reboot the machine.
- [time] specifies when you want the shutdown to perform.
- [message] adds a message that announces the shutdown.
Note: If you need to reboot instead of shut down the system, refer to How To Restart Or Reboot Linux Server From The Command Line.
How to Use the shutdown Command
To use the shutdown command on Linux systems, a root user or a user with sudo privileges is required.
If you use the command without additional arguments, running sudo shutdown in a terminal window executes the shutdown in 60 seconds.
In the image below, see the output received after running the shutdown command.
Shutdown With All Parameters
To view all parameters when shutting down the Linux system, use the following command:
The output displays a list of shutdown parameters, as well as a description for each.
How to Shut Down the System at a Specific Time
To schedule a shutdown, add the [time] argument and specify when you want it to take place. There are two ways to shut down the system at a specific time – using the absolute or relative time format.
The absolute time follows the format hh:mm and allows you to schedule a shutdown at a specified time. The command follows the syntax:
For example, to require a shutdown at 7 AM in the morning, the command is:
Alternatively, use the relative format ( +m ) and schedule a shutdown in a defined number of minutes from the time you run the command. In that case, the command syntax is:
To shut down the system in 20 minutes, run:
How to Shut Down the System Immediately
As previously mentioned, running the shutdown command without any arguments prompts the system to shut down a minute after running the command. However, if you require an immediate shutdown, use:
Another option would be to schedule a shutdown using the relative time format with the value 0, as in the command below:
How to Broadcast a Custom Message
Once you schedule a system shutdown, all users within the system receive a message notifying them of the shutdown. To add a custom message to the shutdown notification to inform the users what is about to take place.
You can add a [message] only if the command also includes the [time] attribute:
For instance, to shut down the system in 20 minutes and broadcast the message System Upgrade, run:
Note: Another way to broadcast messages to users in Linux is via the wall command.
How to Cancel a Scheduled Shutdown
To cancel a scheduled shutdown, use the command:
You can also add a message to notify users that the shutdown is canceled. To do so, add the [message] option (within quotations) to the command above. For example:
This article includes all the basic shutdown commands every Linux user should know. Utilizing this command is a safe way to shut down your system. Also, it is a useful method of informing all users about scheduled shutdowns.
Источник