- Выполнение команд и запуск инструментов в приложении «Терминал» на Mac
- Выполнение команд в оболочке shell
- Прерывание команд
- Повтор ранее введенных команд
- Консоль для маководов: Beyond the GUI
- Лирическое отступление
- Начнём работу
- Продолжаем знакомство с консолью. Команда open
- Пара слов о бандлах
- Скрипт?
- Скрипты AppleScript
- Кратко о других полезных командах Mac OS X
- Что-то типа заключения
- [HOW TO] Launch Application from Terminal?
- gatorparrots
- gatorparrots
- How to Launch GUI Applications from the Terminal
- Opening Mac OS X Applications from the Command Line
- Launching GUI Apps as root from the Command Line
- Creating Shell Aliases for Frequently Launched GUI Apps
- Related
- Enjoy this tip? Subscribe to our newsletter!
- Thank you!
- Related articles:
- 30 Comments
Выполнение команд и запуск инструментов в приложении «Терминал» на Mac
Среду командной строки можно использовать в интерактивном режиме, то есть вводить команду и ждать результат. Вы также можете составить shell-скрипт, который будет выполняться без Вашего непосредственного участия.
Выполнение команд в оболочке shell
В приложении «Терминал» на Mac введите полный путь к исполняемому файлу инструмента, затем введите все необходимые аргументы и нажмите клавишу Return.
Если команда находится в одной из известных папок shell, при вводе имени команды можно не указывать путь. Список известных папок хранится в переменной среды PATH оболочки shell и включает папки, содержащие большинство инструментов командной строки.
Например, чтобы выполнить команду ls в папке текущего пользователя, введите следующую команду в командной строке, затем нажмите Return:
Чтобы выполнить команду в папке текущего пользователя, введите перед командой спецификатор папки. Например, чтобы выполнить MyCommandLineProg , используйте следующую команду:
Чтобы открыть приложение, используйте команду open:
Если при вводе команды отображается сообщение command not found , проверьте правильность написания. Пример:
Прерывание команд
В приложении «Терминал» на Mac нажмите окно Терминала, где выполняется команда, которую Вы хотите завершить.
Нажмите сочетание клавиш Control-C.
Будет отправлен сигнал, который вызывает прерывание большинства команд.
Повтор ранее введенных команд
Введенные в текущем сеансе команды сохраняются, так что Вы можете повторить ранее использованную команду, не вводя ее снова.
В приложении «Терминал» на Mac нажмите клавишу со стрелкой вверх.
Последняя введенная команда отобразится в командной строке.
Продолжайте нажимать клавишу со стрелкой вверх, пока не появится нужная команда, затем нажмите клавишу Return.
Источник
Консоль для маководов: Beyond the GUI
Доброго дня, уважаемые хабравчане-маководы!
Сегодня я расскажу как увеличить эффективность работы в Mac OS X за счёт использования консоли.
Лирическое отступление
Думаю, ни для кого не секрет, что Mac OS является Unix-based системой, но переработанной почти до неузнаваемости. Даже консоль засунули куда подальше — не сразу и найдёшь. И вся система нацелена на использование GUI, при дефолтных настройках даже переключение между кнопками по Tab не работает — без мыши никуда. И тем не менее, Мак — это не только окошки, не только док и лаунчер. Мак это ещё и вся мощь shell скриптов и консоли!
Если Вы пришли из мира M$, то для начала неплохо бы поучить общие команды shell’а, например, по вот этому учебному пособию. Как минимум, нужно усвоить команды перехода по каталогам и способы запуска программ и скриптов.
Если Вы пришли в мир Mac OS из мира Linux’а и FreeBSD, то, скорее всего, знаете как минимум основы shell-скриптинга. Но и для вас в статье может оказаться кое-что интересное, ведь в маке есть уникальные консольные команды, которые так же полезно знать.
Вот о некоторых особенностях маковской консоли далее и пойдёт речь.
Начнём работу
Для начала избавимся от стандартного терминала. Ну, точнее, поставим другой — получше. Я лично предпочитаю iTerm2, который подходит для работы куда лучше системного. Хотя, и у него бывают интересные моменты (см. картинку вверху).
Далее нам могут понадобиться дополнительные инструменты, поэтому устанавливаем MacPorts (хотя, конечно, можно и другой менеджер пакетов). Теперь мы можем ставить нужные консольные утилиты с помощью простых команд. Например, ставим Midnight Commander (он в любом случае может пригодиться), набираем в iTerm2:
После ввода пароля и установки зависимостей и самого mc, можем его запустить, как вы уже догадались, командой mc .
О ужас! Нам понадобятся функциональные клавиши, а они нажимаются только через Fn+F15 , что же делать? Ну как что — лезть в системные настройки и выключать это. Иначе сложно будет с mc работать.
Ещё одно важное замечание: кури мануалы если что-то не понятно, набираем в консоли man команда — и получаем подробное описание команды. (Кстати, для выхода из просмотра мануала надо просто нажать Q).
Продолжаем знакомство с консолью. Команда open
Легко можно заметить, что mc показывает куда больше файлов и папок, чем Finder. Конечно, можно поставить хак для него, чтобы он отображал такие файлы, но не все это любят. Так что остаётся лишь пользоваться Cmd+Shift+G и вводить вручную имя папки. Но данный способ не особо удобен: нет автокомплита, нет возможности видеть скрытые файлы. Теперь вернёмся к терминалу. В Mac OS X есть замечательнейшая команда open , которая действует так, как будто пользователь сделал даблклик на файле или папке в Finder — открывает файл, бандл или ссылку в связанной программе, открывает папку в Finder’е. Вот простой пример работы с этой командой: заходим с помощью mc в скрытую папку (например, /etc/) и набираем:
Wuala! Файндер отобразил нам нашу системную папку! Но это ещё не всё, ведь скрытые файлы всё ещё не видны. Для примера, откроем наш .profile :
И — опа! — скрытый файл открылся в TextEdit! Всё предельно просто.
Пара слов о бандлах
Это всем известно, но на всякий случай повторю: обычные программы в Mac OS X на самом деле являются папками с расширением .app и особым образом устроенным содержимым. Убедиться в этом легко: открываем в Finder папку /Applications/ и делаем Ctrl+Click (либо Right-Click , если хотите) на любой программе и выбираем «Показать содержимое пакета».
Из консоли это так же очень хорошо видно: mc отображает эти программы именно как папки. И как же запустить из консоли GUI-программу, спросите вы? Очень просто, есть даже два способа.
Способ первый, простейший:
Программа будет запущена и консоль будет свободна для дальнейших действий.
Способ второй, интересный:
Программа будет запущена, но консоль не освобидится — она будет ждать завершения программы и выводить всё, что программа захочет вывести в неё. То есть, таким образом можно посмотреть рабочий лог некоторых программ.
Ещё одно очень важное различие между этими двумя методами: второй позволяет запустить два экземпляра программы, в то время как первый активирует уже запущенную, буде такая имеется. Так что через консоль можно решить и эту проблему (хотя, скорее фичу) макоси: через Finder, док и лаунчер запустить два экземпляра программы нельзя, а вот из консоли — пожалуйста, хоть двадцать два.
Скрипт?
Расскажу вкратце что из себя представляет shell-скрипт. По сути — это обычный текстовый файл, содержащий серию команд для выполнения. Самый простой скрипт просто запускает последовательно все команды. Скрипты посложнее могут иметь условия, циклы и функции, то есть, скрипт может быть весьма большой и сложной программой. Основной плюс таких скриптов — на их службе вся мощь консольных утилит из мира unix, что с лихвой компенсирует бедность языковых конструкций. Приведу простой пример скрипта, который преобразует все файлы .png в текущей директории, уменьшив их размер до 200 пикселей в ширину или высоту.
Пример простейший, но он демонстрирует главное: в скриптах сокрыта великая сила.
Скрипты AppleScript
В Mac OS X имеется несколько встроенных механизмов по автоматизации действий. Один из очень распространённых — AppleScript, для которого есть и графический редактор-запускатор. Но использовать такие скрипты можно и из консоли, для этого есть особая утилита — osascript . Использовать её можно так:
Не буду углубляться в AppleScript, он заслуживает отдельной статьи, и даже не одной. Так что рекомендую почитать справку или гугл по нему.
Главное: Вы можете комбинировать shell-скрипты со скриптами AppleScript, чтобы добиться максимальной гибкости в работе! К примеру, я использую такие вот смешанные скрипты для автоматической стилизации образа диска: сам диск создаётся с помощью shell (см. ниже), а фон и расположение элементов в образе задаётся с помощью AppleScript.
Есть ещё Automator, но он совсем уж GUI-шный, так что в данной статье его рассматривать бессмысленно. Он, конечно, полезный, но до мощи консоли не дотягивает.
Кратко о других полезных командах Mac OS X
Полный (ну, почти) список уникальных для макоси команд можно найти в одной хорошей статье (хотя сведения там немного устарели), я же вкратце расскажу о наиболее интересных.
Для работы с образами дисков имеется консольная утилита hdiutil . Пара примеров работы с ней:
Более подробно про возможности можно узнать из man hdiutil .
Если Вы — разработчик программ для макоси, то наверняка знаете о такой замечательной вещи, как Info.plist, да и вообще о plist’ах. Так вот, есть очень удобная утилита, позволяющая конвертировать .plist в .bplist, то есть, в более быстрый и лёгкий бинарный формат плиста.
Если хотите позаниматься ерундой, то можно из консоли проговорить любой текст. Для этого есть утилита say .
Так же можно задавать голос, которым мак будет с нами говорить:
Одна беда — по-умолчанию говорит эта штука только по-английски.
Теперь снимем скриншот командой из консоли.
Так же из консоли можно конвертировать текст между различными форматами. Например, можно переконвертировать .doc файл в HTML:
Так же textutil умеет преобразовывать кодировки.
Для изменения системных (и не только) настроек, можно использовать команду defaults . Используем её во благо! Включим наконец отображение скрытых файлов и папок в Finder!
Файндер автоматически перезапустится и теперь будет отображать скрытые файлы и папки! Но опять таки, это не всем нравится, так давайте это выключим, пока родителикто-нибудь не испугался или не удалил нужных файликов. Для сокрытия в уже указанной команде поставьте 0 вместо 1. Ну и для примера, ссылка на статью, где описано много твиков с помощью этой команды.
Что-то типа заключения
Ну что ж, мы разобрали некоторые интересные возможности консоли в Mac OS X. Статья, разумеется, не претендует на полноту и является, скорее, «заманухой» для вовлечения маководов в shell-скриптинг да и вообще в консоль.
Источник
[HOW TO] Launch Application from Terminal?
Registered
How do I launch an application from the terminal?
Thanks for the help
gatorparrots
The command is simply open (which can also be used for opening directories). The most basic example of launching an application:
open /path/to/some.app
More complex possibilities also exist:
open «/Volumes/Macintosh HD/foo.txt»
opens the document in the default application for its type (as determined by LaunchServices).
open /Applications/
opens that directory in the Finder.
open -a /Applications/TextEdit.app «/Volumes/Macintosh HD/foo.txt»
opens the document in the application specified (in this case, TextEdit).
open -e «/Volumes/Macintosh HD/foo.txt»
opens the document in TextEdit (the -e option specifies TextEdit).
open http://www.apple.com/
opens the URL in the default browser (lynx, naturally *wink*)
open «file://localhost/Volumes/Macintosh HD/foo.txt»
opens the document in the default application for its type (as determined by LaunchServices).
open «file://localhost/Volumes/Macintosh HD/Applications/»
opens that directory in the Finder.
Registered
gatorparrots
If you need to edit a root-owned system configuration file, it is possible to do so with a graphical text editor, for example.
Carbon Applications
Older Carbon applications have to be run via LaunchCFMApp because they are in the wrong binary format for Mac OS X, so LaunchCFMApp handles the necessary translation.
To launch a Carbon application directly (without using open), one has to actually run LaunchCFMApp, giving it the application as an argument:
/System/Library/Frameworks/Carbon.framework/Versions/Current/Support/LaunchCFMApp ‘/path/to/some/application’ .
open can also be used to launch Carbon applications. open simulates a double click, hence the package name is given, rather than the full path to the executable. open‘s main advantage is in opening documents since it uses the Finder’s ‘open with’ database of what applications open what documents, and in opening Carbon applications. Using open, most of the difficult work is done for you: open ‘/path/to/some/application’
To launch a Carbon application with root privileges, you have to prepend sudo -b to the first command above. Here is a specific example:
sudo -b /System/Library/Frameworks/Carbon.framework/Versions/Current/Support/LaunchCFMApp ‘/Applications/BBEdit Lite 6.1/BBEdit Lite 6.1 for OS X’
Cocoa Applications
To run applications as root, we use sudo. However combining open and sudo in this form:
sudo open /path/to/some.app
results in sudo running open as root, but open still opens the application as the original user.
Therefore, the longer method of specifying the full path name for Cocoa applications (not just to the .app package, but to the actual executable):
sudo «/Applications/TextEdit.app/Contents/MacOS/TextEdit»
(The -b flag can be specified to run appropriate applications in the background. You can’t use & and sudo when an authentication password is required, necessitating the need for the -b flag.)
Источник
How to Launch GUI Applications from the Terminal
We all know how to launch applications from the GUI with a double-click on the icon or clicking on the app in the Dock, and there are numerous ways to do so, and they’re all relatively speedy. If you spend a decent amount of time with the command line though, it’s nice to be able to launch Mac apps directly from there as well. Also, the Terminal has a fair share of applications that run in text based mode, but maybe you wanted to edit a text file in the OS X GUI app TextWrangler rather than the text based nano or vim.
We’re going to demonstrate how to launch any graphical Mac app from the command line of OS X, including how to open specific files from the command line with a GUI app, and how to edit and open those files with root access if it’s necessary.
Opening Mac OS X Applications from the Command Line
The Terminal command to launch OS X gui apps is appropriately called ‘open’ and here is how it works at it’s most simple:
open -a ApplicationName
That will open the defined app named “ApplicationName”.
But open is much more powerful than that. If you just type ‘open’ at the command prompt, you’ll return the basic help file with details on how to properly use the command with a variety of flags and syntax. While the open command exists in all versions of Mac OS X, the abilities vary somewhat depending on what version of OS X the Mac is running. Nonetheless, in modern releases this is what you’ll see:
In other words, example simple command syntax could look like the following, opening “ApplicationName” with the file located at the path ‘/file/to/open’:
open -a ApplicationName /file/to/open
You’ll note you don’t need the full path to the application name, but you would need the full path to a file name.
The usage is likely self explanatory to those who have experience in the command line environment, but for those who are new to the Terminal, don’t be too confused, it is easy to use and we’ll explain. For example, if you want to edit /etc/motd with TextWrangler to change your Message of the Day, but you hate the command line editors nano and vi, here is what you’d type:
$ open -a TextWrangler /etc/motd
Now you can edit these files in the familiar GUI. open is smart enough to know that when you apply the -a flag, you are launching an application so you don’t need to type in its full path. Obviously, it’ll still need the full path to the file you’re editing though.
There are many other usages for the open command rather than just editing text files, so use your imagination and get creative. open could be particularly useful to system administrators who utilize it in a shell script, perhaps to launch a specific GUI application at a scheduled time.
Also worth noting is that if you are launching an application with spaces in its name, you’ll want to add a backslash after each word, opening Adobe Photoshop CS would look like this:
$ open -a Adobe\ Photoshop\ CS
Launching GUI Apps as root from the Command Line
You can even open files with sudo by using the open command if you need to edit a file as root, for example:
sudo open -a TextEdit /tmp/magicfile
This will launch the target file into the desired application as root user, giving full root privileges to edit and modify the file, which is quite helpful for editing many system files. Of course, don’t modify any system file if you don’t know what you’re doing.
Creating Shell Aliases for Frequently Launched GUI Apps
So it’s kind of a pain in the butt to type a full command repeatedly, or to type out all that out over and over again, right? Well let’s make it easier by assigning an alias to an application that gets frequently launched. We’ll take the aforementioned Adobe Photoshop app as an example since the file name is lengthy, so here’s how we’ll do this with the Mac OS X default Bash shell:
First launch the profile or .bash_profile into a text editor:
Ignoring whatever else may be in this file (it could be empty also), add the following to a new line:
alias photoshop=»open -a Adobe\ Photoshop\ CS»
This creates an alias, so that the “open -a Adobe\ Photoshop CS” command is now shortened to simply ‘photoshop’. Save .profile, and you’re on your way! You can use the alias command in conjunction with open for virtually anything, just be sure to pick an alias to a command that doesn’t already exist.
The open command is really handy as you can see, if you have any other great uses for it in OS X, be sure to let us know in the comments.
Related
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.
Related articles:
30 Comments
Thanks for this article – as a Late 2012 Mac Mini user, I have struggled to figure out how to configure X-Plane11 to run real time. I ran the benchmark:
open -a X-Plane.app –args –fps_test=1 –load_smo=Output/replays/test_flight_c4.fdr –pref:_is_ful_ALL=1 –pref:_x_res_full_ALL=1280 –pref:_y_res_full_ALL=720 –pref:_bpp_full_ALL=32
and got:
FRAMERATE TEST: time=93.5, frames=2162, fps=23.12
GPU LOAD: time=93.5, wait=5.7, load=6.1%
so I knew if I made my X-Plane settings 1280×720 windowed, I could get real-time performance, and it works!
How do I write it so that it opens a file, but not a specific file, one that a program could choose?
There is another way of dealing with spaces in this case.
Instead of:
open -a Adobe\ Photoshop\ CS
You could use:
open -a ‘Adobe Photoshop CS’
So, the alias for this would be:
alias photoshop=”open -a ‘Adobe Photoshop CS’ ”
Also, notice the space in the end of the alias (after the CS’ part). It allows you to do more with the command. Example:
Let’s say we got an alias for Chrome. It looks like this:
alias chrome=”open -a ‘Google Chrome’”
In the terminal you want to open a text file with Chrome. Let’s say it’s called ”mydocument.txt”. You will try this in the Terminal:
Which will return an error like this:
Unable to find application named ‘Google Chromemydocument.txt”
Using the alias here is the same as:
open -a ‘Google Chrome’mydocument.txt
So, instead of this we put a space in the alias:
Alias before: alias chrome=”open -a ‘Google Chrome’”
Alias after: alias chrome=”open -a ‘Google Chrome’ ”
Now, when using this space and open a file with the application Alias is equal to:
open -a ‘Google Chrome’ mydocument.txt
The result is that Chrome will open the file mydocument.txt in the browser. Of course, the application itself should be able to display the file.
The same can be used for commands like:
sudo
Allowing you to enable sudo on aliases.
So, the alias for sudo would be like this:
alias sudo=”sudo ”
In that way, you can use (just a example, there is almost no reason at all for this in real world use for Google Chrome):
sudo chrome
To break it down:
-> open -a
As described in the article, the command that will ”Open with the specified application”.
-> ‘Google Chrome’
The exact name of the application as displayed in the Finder without the .app extension.
-> mydocument.txt
The path to the file that will open. In this example, the file is located in the same working directory. But if i was to open a file located in the folder ”Text files from Chanderton” at the Desktop. it would look like this if i was to drag and drop the file in the Terminal after the alias name:
chrome /Users/YourUserName/Desktop/Text\ Files\ from\ Chanderton/mydocument.txt
or not using the application Alias:
open -a ‘Google Chrome’ /Users/YourUserName/Desktop/Text\ Files\ from\ Chanderton/mydocument.txt
—
For the ones that like things to be over the top. You can create the alias like this:
alias chrome=”say ‘Starting Chrome’ | open -a ‘Google Chrome’ ”
or:
alias chrome=”echo ‘🗣 Starting Chrome 👀 ‘; wait | say ‘Starting Chrome’; wait | echo ‘👍 Yeah!’; open -a ‘Google Chrome’ “
[…] X with root privileges, but it’s not just a matter of prepending sudo to the otherwise useful open command, because ‘open’ launches apps as the original user, with or without sudo. The solution […]
How do I also pass command line switches to the app? I’m trying to open VLC with the -v –color switches. (I saw them on the VLC wiki, maybe these are windows only options but the wiki doesn’t specify that.)
Hi
Thanks to you, I can now open my files in Preview using the command line. Now I need to “Save as” in Preview using the command line. Does anyone know how to do it?
Thanks!
Sofia
Try this for a “Save As” replacement in OS X Lion
Hi Matt
Thanks for your reply. but I need to “save as” or “export” from the command line.
I need to convert more than hundred images from .pdf to bmp and to eps and I want to do it in a script. For that, I would like to open these files in Preview and save them in the new format, everything from the command line. Is it possible to “save as” in Preview from the command line?
Thanks
Sofia
[…] command line users, use the “open” command to pass wildcards to ImageOptim for easy scripting and bulk image compression like […]
[…] your hard disk name for this walkthrough. Now here’s the interesting part, typically you can launch applications from the Terminal with the ‘open’ command, but the Lion Recovery drives have a stripped down set of […]
[…] Line, Mac OS X, Tips & Tricks – July 18th, 2011 – Leave a Comment Using the command line open tool, you can immediately launch any URL from the Terminal into the default web browser. The syntax […]
[…] tells the command to only open the file if the header was successfully downloaded. Using ‘open‘ will open httpheader.txt in the default GUI text editor, which is generally Text Edit, but […]
[…] application in Mac OS X with a little command line magic. Using the ‘open’ command to launch GUI apps from the Terminal, we can run a new instance of any app, even if it is already […]
so how do i open a folder in the terminal to have it open as a gui folder? (not cd command – that just opens it in the terminal itself)
for instance can i say
open /etc? and have the gui window pop up?
so open /etc would open /etc in the Finder
[…] osxdaily David Miller O’reilly wiki bash ss64 This entry was posted in bash, osx, terminal. Bookmark […]
[…] How to Launch GUI Applications from the Terminal – OS X Daily (tags: alias command bsd howto macosx terminal tip open apple launch opensource unix tips osx shell macos applications application commandline macintosh mac from gui article os guide) […]
[…] Come lanciare le applicazioni di Mac OS X dalla linea di comando (Terminale) How to Launch GUI Applications from the Terminal – OS X Daily. […]
anyone know how I can do adobe updates through the command line.? I want to send unix commands with ARD to adobe updater to install the updates.
a search by Pacifist (of the base.pkg and the bsd.pkg) on the osx leopard retail installer dvd turns up NO RESULT for a command named “open”!
are you sure that this command was available even in tiger?!
you really need to be more precise about the context of the ‘open’ command vis a vis the (bash) shell …
what are the prerequisites & dependencies that must already be setup in order – for instance – to run the ‘open’ command from the osx installer dvd?!
i have created a custom boot disk that adds an extra folder of diagnostic utilities to help troubleshooting … but none of those apps will run even when my local path already is located at the (new) special utility folder (ls sees the contents of the directory just fine).
i suspect that apple’s path info (on the bootable dvd) is locked down, so osx can not even see the ‘open’ command (because it is not part of the bsd userland that is loaded from the boot dvd) — if this is true, then i suppose it is just a matter of editing some config files (on the disk image) before burning another custom installer, correct?
If so, then it would be useful for you to articulate a flight-check/checklist of which files must be setup in what way in order to allow a given functionality under what circumstances!
obviously, my specific example is the one i am most interested in 🙂
ps: it should be noted that the reason i am want to launch specific apps /from the installer disc/ is precisely because i do not wish to complete the only type of installation that is available to me (in this case, unfortunately, a fresh install, which will wipe my current partition) … i have not backed it up yet (long story) but i want the chance now to dump everything on the NAS – alas, firewire target mode is not available because that port seems dead on my Mini 🙁 …
i dont know exactly what app will allow me to backup to the NAS (carbon copy cloner, disk utility, etc), but no matter which one i will need to use, i know i will need to use the ‘open’ command from a bash shell that has a default restriction on how much of the global path is visible to the bootable installer dvd!
i am sure i am not the only person who will be ever caught with a blown-up partition on a machine that cant use firewire target mode – so some clarification about the prereqs in the path environment variables would be super appreciated!
Источник