Shutdown ��� mac os

Перезагрузка компьютеров с помощью Терминала на Mac

Чтобы перезагрузить компьютер немедленно или в определенное время с помощью приложения «Терминал», используйте команду shutdown или systemsetup . В следующих примерах показано несколько способов использования этих команд. Полная информация о них приведена на man-странице команды shutdown и man-странице команды systemsetup.

Совет. Можно легко перезагрузить Mac, выбрав меню «Apple»

> «Перезагрузить», или выключить компьютер, выбрав меню «Apple» > «Выключить». См. раздел Выход из системы, переход в режим сна, перезагрузка и выключение Mac.

Перезагрузка локального компьютера

В приложении «Терминал» на Mac введите следующую команду:

Немедленная перезагрузка удаленного компьютера

В приложении «Терминал» на Mac введите следующие команды:

Вместо admin укажите короткое имя учетной записи пользователя на удаленном компьютере.

Вместо computer укажите IP-адрес или имя хоста удаленного компьютера.

Перезагрузка удаленного компьютера в определенное время

В приложении «Терминал» на Mac введите следующие команды:

Вместо admin укажите короткое имя учетной записи пользователя на удаленном компьютере.

Вместо computer укажите IP-адрес или имя хоста удаленного компьютера.

Вместо hhmm укажите время перезагрузки удаленного компьютера (в формате ччмм).

Автоматическая перезагрузка при сбое питания

В приложении «Терминал» на Mac введите следующую команду:

Вместо seconds укажите количество секунд, по прошествии которых компьютер должен загружаться после сбоя питания. Значение должно быть равно 0 (нуль) или быть кратно 30.

Примечание. Можно также задать настройки энергосбережения, чтобы компьютер Mac автоматически перезагружался после сбоя питания.

Источник

Как выключить Mac через командную строку

Продвинутым пользователям Mac может понадобиться выключить компьютер через командную строку. Это может пригодиться для удалённого управления с помощью SSH, при однопользовательском режиме и когда возникают проблемы с работой и управлением системой.

Есть несколько способов выключить Mac через командную строку, мы рассмотрим два самых простых.

Командная строка на Mac предлагает много команд для выполнения различных заданий и системных функций, так что и отключить компьютер через неё тоже можно.

Важное предупреждение: отключение Mac через командную строку происходит мгновенно. Не всплывает окно с подтверждением или предупреждением, не даётся время на сохранение документов или закрытие программ. Mac сразу же устранит все активные процессы и моментально выключится. Это может привести к потере данных, так что перед использованием команды нужно подготовить компьютер к отключению.

Отключение Mac командой «shutdown»

Чтобы отключить Mac с помощью команды «shutdown», нужно использовать «-h» и указывать время «now». Команда будет выглядеть так:

sudo shutdown -h now

Как только вы нажмёте кнопку «return», Mac закроет все программы и завершит все процессы, а затем отключится. Диалогов с предупреждениями не будет, это произойдёт моментально.

Если вы не зарегистрированы как root-пользователь, вам нужно будет добавить перед командой «sudo», чтобы она получила привилегии суперпользователя.

Если хотите попробовать этот способ (и у вас всё сохранено и закрыто), следуйте инструкции:

  1. Откройте командную строку (через /Applications/Utilities/folder)
  2. Введите следующую команду:

sudo shutdown -h now

3. Нажмите кнопку «return» и введите административный пароль, чтобы выключить Mac.

Вы можете использовать «-h» для указания времени и даты отключения компьютера. Например, «in 30 minutes» (через 30 минут), но, если вы хотите сразу же выключить Mac, нужно вводить «now».

Отключение Mac через несколько минут

Если вы хотите отключить компьютер попозже, можно ввести следующую команду:

sudo shutdown -h +30

«30» можно заменить любым двузначным числом, и Mac выключится через столько минут. Если вместо «30» ввести «2», компьютер отключится через две минуты.

Отключение Mac командой «halt»

Команда «halt» тоже выключает Mac моментально.

  1. Откройте Terminal.app.
  2. Введите следующую команду:

3. Нажмите «return» и введите пароль.

В использовании «halt» или «shutdown» нет никакой разницы. Пользуйтесь командой, которую вам легче запомнить.

Команду «shutdown» можно использовать и для перезагрузки, для этого вместо «-h» надо ввести «-r».

Обычным пользователям лучше отключать компьютер через меню Apple, так что этот способ подойдёт тем, кто и так регулярно пользуется командной строкой.

Источник

Выключение и перезапуск системы через Терминал

Тема может и не самая новая, и некоторые команды вы наверняка знаете. Данный метод перезагрузки и выключения компьютера далеко не самый быстрый и привычный. Если система стабильно работает, загружается и выгружается без проблем, лучше использовать стандартные способы. Некоторые из них уже были описаны раньше. С того времени ничего не изменилось 😀 .

Читайте также:  Wifi адаптер для linux mint

Выключение через Apple-меню — это самый понятный и правильный способ завершения работы. О нем все знают, поэтому останавливаться на нем нет необходимости. Практически тоже самое можно сказать и о диалоговом окне выключения компьютера, которое открывается легким нажатием на кнопку питания. Другим способом его можно вызвать, прижав Control + Eject. Далее выбираете нужное действие.

Терминал

Зачем же нужно использовать терминал для выключения/перезагрузки? Для обычного пользователя скорее всего и не надо. А вот разработчикам, администраторам, и другие пользователям, которые работают с системой удаленно – очень даже полезно. Ну и не забываем о «линуксоидах» (без обид 🙂 ) – им всегда приятно понимать, что практически любой элемент системы они могут прощупать и изменить.

Удаленный доступ можно использовать с другой мак-машины (его нужно сначала активировать, и знать IP компьютера), запустив такую команду:

Подставляете правильные username и ip_address и в результате увидите запрос пароля. Дальше, все ниже описанные команды можно запустить в этом окне Терминала, и они будут восприняты удаленной системой как локально запущенные.

Команды выключения:

— «правильное» выключение машины. Параметр now можно заменить другим временем, когда система должна выключиться.

— фактически, то же самое, но без всяких красивых уведомлений пользователей.

— быстрое выключение (только чистка кэша файловой системы)

osascript -e ‘tell app «system events» to shut down’

— выключение через ж… извините, через AppleScript

Команды перезагрузки:

— «правильная» перезагрузка в указанное время (в данном случае — сейчас же)

— перезагрузка «системная» (без уведомлений)

— быстрая перезагрузка (с чисткой кэшей, как и в halt)

osascript -e ‘tell app «system events» to restart’

— перезагрузка через скрипт

Выполнение таких команд как shutdown или halt требует права администратора. Поэтому нужно вводить перед ними sudo.
Есть также некоторые параметры, которые могут пригодится. Например halt -nq пригодится, когда машину нужно выключить немедленно. Часть -n значит, что завершение работы осуществляется без очистки системного кэша файловой системы (конечно же, не рекомендуется использовать каждый день).

Для дополнительной информации о командах и доступных параметрах в Терминале введите:

Получите полное описание возможностей и опций.

Думаю, не стоит напоминать, что случаи ЭКСТРЕННОГО завершения работы случаются крайне редко. Ну, разве что, после очистки Корзины, где удивительным образом оказались важные документы. Тогда одна из команд должна пригодится. А если вы пользователь, который живет обычной жизнью, решает ежедневные нехитрые операции, то скорее всего с Терминалом мало знакомы. А по этому лучше с ним не играть. Это серьезный инструмент и в неумелых руках может привести к грустным последствиям.

Источник

How to Shutdown a Mac from Terminal

Advanced Mac users may wish to shut down a computer from the command line. This can be helpful for remote administration with ssh, in situations where a Mac is booted into Single User Mode, or many other circumstances of troubleshooting and systems administration.

There are several ways to shut down a Mac from the command line, we’ll cover two of the most simple methods using easy syntax.

The Mac Terminal offers many commands for handling various tasks and system functions, and so naturally the command line also offers a method to shutdown a Mac computer from the Terminal as well.

An important word of warning: shutting down a Mac through the command line happens instantaneously. There is no confirmation, no warning dialog, no stopping to save documents, no asking to close apps or save anything. Instead, the Mac will instantly terminate any and all activity going on and immediately shut down the computer. This could lead to data loss, so be sure you are ready to turn off a Mac if you issue these commands.

Shutting Down a Mac from Command Line with ‘shutdown’

Apt for the name, the ‘shutdown’ command can shutdown a Mac as well as reboot a Mac via Terminal. To turn off a Mac with the shutdown command, you will use the -h flag and give the time for ‘now’ making the syntax like so:

sudo shutdown -h now

As soon as you hit return and authenticate the command, the Mac halts and kills all applications and processes and shuts the computer down. There is no warning and no dialog, it happens instantly.

Unless you’re actively logged in as the root user (via single user or otherwise), you will need to prefix the shutdown command with ‘sudo’ to give the command superuser privileges, thus requiring an administrative password.

If you feel like trying this yourself (and you have all data saved and nothing important open) do the following:

  1. Open the Terminal in Mac OS (found in /Applications/Utilities/ folder)
  2. Enter the following command syntax exactly:

sudo shutdown -h now

  • Hit the return key and authenticate with an administrative password to immediately shut down the Mac
  • Читайте также:  Драйверы устройств linux третья редакция

    The Mac will immediately shut down. No data is saved and no dialogs are confirmed, the shut down happens instantly.

    You can also use the -h flag to set a time or date for shutting down the computer, for example in 30 minutes, but if you want to shut down the Mac instantly you would use the ‘now’ parameter with the -h flag rather than a number.

    Shutting down a Mac in XX Minutes from the Command Line

    If you do feel like putting a delay on the shutdown, you can use the following command syntax instead:

    sudo shutdown -h +30

    Replace “30” with any other number of minutes to shut down the Mac in that amount of time. For example if you put “2” instead of 30 then you would shut down the Mac in 2 minutes.

    Shutting Down a Mac via Terminal with ‘halt’

    The ‘halt’ command can also instantly shut down a Mac via the command line. The process and syntax for ‘halt’ to turn off a Mac is as follows:

    1. Open the Terminal .app in Mac OS
    2. Enter the halt command syntax exactly as described:
  • Hit the return key, authenticate with sudo to instantly shut down the Mac
  • Whether you use ‘halt’ or ‘shutdown’ does not matter really, it’s mostly preference and what you can remember when necessary.

    By the way, the shutdown command can also be also be used to restart a Mac from the command line by using the -r flag instead of the -h flag.

    Keep in mind that for most users the command line approach is not going to be better or faster than accessing the  Apple menu Shut Down option or using the power button keyboard shortcuts, this is really aimed at advanced users who are already at the command line anyway.

    Enjoy this tip? Subscribe to our newsletter!

    Get more of our great Apple tips, tricks, and important news delivered to your inbox with the OSXDaily newsletter.

    Thank you!

    You have successfully joined our subscriber list.

    19 Comments

    It’s just like windows they have shutdown commsnd when you updating the windows patches.i got no time to wait to shutdown i just type the command on search button or you cmd .
    this is just basic commsnd for unix wait until you need to search some hidden files more command. 20 years ago mac os purely unix command when it comes restore the mac but now apple make it simple .

    Great tip I learned how to shut down the Mac from the command line with this. I use to use shutdown -h now in Linux but had long forgotten the commands.

    Today we have only seven ladder manufacturers in the US, down from >100. Why; not globalization, nor a decline in the market but rather the lawsuits from people who fell off ladders and sued all the small operations. The desire for an idiot-proof world is here again on this thread. CLI and its risk/benefits are not for the foolhardy. People like this are the reason why construction trucks make that beeping noise when backing-up.

    The “reboot” command was not listed, but is sometimes very handy.

    Well, for those of us who use the Terminal this trick is appreciated. Thank you.

    This advice is just plain wrong and will lead to corruption and lost data if you follow it. DO NOT follow this advice.

    Both commands send programs a UNIX style shutdown command. GUI programs do not expect this and will terminate WITHOUT giving you the chance to save your data or clean themselves up. (Specifically, Cocoa apps do not see applicationShouldTerminate: or the kAEQuitApplication Apple Event)

    The correct way to safely shutdown from the command line is “osascript -e ‘tell app “System Events” to shut down’”

    Sam, you’re wrong. This shuts down a Mac from the command line. Did you even bother read the article? Obviously not. There are multiple warnings that it does not request a data save. There’s a giant paragraph at the beginning of the article.

    How did you manage to get this far without reading the article? Maybe this site needs a system to verify that people read the article before they can comment.

    “An important word of warning: shutting down a Mac through the command line happens instantaneously. There is no confirmation, no warning dialog, no stopping to save documents, no asking to close apps or save anything. Instead, the Mac will instantly terminate any and all activity going on and immediately shut down the computer. This could lead to data loss, so be sure you are ready to turn off a Mac if you issue these commands.”

    Читайте также:  Line 6 monkey windows 10

    Also to say it is “wrong” is itself wrong, because “wrong” is by definition incorrect. The article is correct, even if you don’t agree with it. That makes it TRUE.

    Why don’t you do your own research, type “man shutdown” into the command prompt and you will see that it is REAL and TRUE. Facts matter.

    You are wrong about reading the man page. The man page was never updated for macOS. Read the bottom of the man page. It says “BSD December 11, 1998”. That means Apple never updated the man page for OS X, otherwise it would say DARWIN or macOS (try man diskutil or pmset). Therefore do NOT trust the information.

    There is NO reason to use BSD shutdown unless the system is stuck. There is a perfectly good command line method which I provided, which is safe and does not result in data loss.

    In general, Apple does recommend applications or users work with the BSD interfaces and utilities in macOS. This is a prime example why.

    Sam if you’re booted into recovery or single user as root and need to shutdown a Mac, how do you propose doing that?

    The answer is the shutdown command.

    I use `osascript -e ‘tell app “System Events” to shut down’` and worked just fine.

    “*** FINAL System shutdown message from user@host ***
    System going down IMMEDIATELY”

    Then I had to go across town to locally switch it back on. Any osascript magic to switch the machine back on, remotely?

    If you haven’t found it already, you’re going to groan a bit.

    osascript -e ‘tell app “System Events” to restart’

    This is idiotic, why risk a terminal mistake when you can simply go to Apple upper left of screen and click shut down. If you are connected remotely this works exactly the same.

    I guess OSXDaily is just running out of good advice, and posting bad in it’s place.

    “no way” you personally should definitely stick to novice level material like your little Apple menu trick because this is obviously over your head, which is fine, you’re a novice level user. Everyone starts somewhere.

    If you don’t know why people use the Terminal or would want to shutdown from the command line you should probably not comment about it, it makes you sound even less intelligent than your comments already are.

    Actually shutting down a Mac by command is very useful to every sysadmin.

    If you don’t understand a subject but you attack that subject because you don’t understand it yourself, that makes you the idiot. You’re being willfully ignorant. In fact, you would be less of an idiot yourself if you bothered to learn a thing or two.

    I understand the subject perfectly well, have been a system admin and senior level repair for Apple for over two decades.

    Instead of whining and trash talk prove me wrong.

    Bottom line doing ANYTHING via terminal remotely is a risk that no experienced tech would ever do when they can do it via the user commands.

    Well… your nick certainly suits you… because there is NO WAY you’ve been a sysadmin for over two decades and haven’t happened upon a situation where you’ve needed to shutdown a Mac via the CLI.

    For one, as a true sysadmin, I SSH into our Macs (typically moreso the servers – Minis, etc – but also the workstations on occasion), and shutting down/restarting via command line is the quickest option.

    For two, it’s what a true sysadmin would be used to, having administered mixed platform environments including *NIX, Windows and Mac systems.

    For three, using the shutdown command via the terminal CLI is no more “dangerous” than choosing the wrong menu item or clicking the wrong button on a GUI… and it’s 10x’s more efficient because I don’t have to stop and reach for a mouse.

    So, really, you’re definitely not inspiring confidence in your sysadmin skills right now… especially if you don’t think you can accurately type an 8 letter command in a terminal.

    obviously if you are using this method is because the regular one did not work! duh

    you’re wrong…
    I just used the command as the top bar did not want to pop up. Shutting down with the buton is not too healthy for the HDD.

    Источник

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