Command line and mac os

Keyboard shortcuts in Terminal on Mac

Use these shortcuts to save time when using Terminal.

Work with Terminal windows and tabs

New window with same command

New tab with same command

Show or hide tab bar

Show all tabs or exit tab overview

New remote connection

Show or hide Inspector

Edit background colour

Make fonts bigger

Make fonts smaller

Split window into two panes

Close split pane

Close other tabs

Scroll to bottom

Edit a command line

Reposition the insertion point

Press and hold the Option key while moving the pointer to a new insertion point

Move the insertion point to the beginning of the line

Move the insertion point to the end of the line

Move the insertion point forwards one character

Move the insertion point backwards one character

Move the insertion point forwards one word

Move the insertion point backwards one word

Delete the line

Delete to the end of the line

Delete forwards to the end of the word

Option-D (available when Use Option as Meta key is selected)

Delete backwards to the beginning of the word

Delete one character

Forward-delete one character

Forward Delete (or use Fn-Delete)

Transpose two characters

Select and find text in a Terminal window

Select a complete file path

Press and hold the Shift and Command keys and double-click the path

Select a complete line of text

Triple-click the line

Double-click the word

Press and hold the Shift and Command keys and double-click the URL

Select a rectangular block

Press and hold the Option key and drag to select text

Copy without background colour

Copy plain text

Paste the selection

Paste escaped text

Paste escaped selection

Find using the selected text

Jump to the selected text

Open the character viewer

Work with marks and bookmarks

Mark as bookmark

Mark line and send return

Send return without marking

Insert bookmark with name

Jump to previous mark

Jump to next mark

Jump to previous bookmark

Jump to next bookmark

Clear to previous mark

Clear to previous bookmark

Select between marks

Other shortcuts

Enter or exit full screen

Show or hide colours

Open Terminal preferences

Typing Command-Full Stop (.) is equivalent to entering Control-C on the command line

Soft reset terminal emulator state

Hard reset terminal emulator state

Hold down the Command key and double-click the URL

Add the complete path to a file

Drag the file from the Finder into the Terminal window

Export selected text as

Reverse search command history

Toggle “Allow Mouse Reporting” option

Toggle “Use Option as Meta Key” option

Show alternate screen

Hide alternate screen

Open man page for selection

Search man page index for selection

Complete directory or file name

On a command line, type one or more characters, then press Tab

Display a list of possible directory or file name completions

On a command line, type one or more characters, then press Tab twice

Источник

Консоль для маководов: Beyond the GUI

Доброго дня, уважаемые хабравчане-маководы!

Сегодня я расскажу как увеличить эффективность работы в Mac OS X за счёт использования консоли.

Лирическое отступление

Думаю, ни для кого не секрет, что Mac OS является Unix-based системой, но переработанной почти до неузнаваемости. Даже консоль засунули куда подальше — не сразу и найдёшь. И вся система нацелена на использование GUI, при дефолтных настройках даже переключение между кнопками по Tab не работает — без мыши никуда. И тем не менее, Мак — это не только окошки, не только док и лаунчер. Мак это ещё и вся мощь shell скриптов и консоли!

Если Вы пришли из мира M$, то для начала неплохо бы поучить общие команды shell’а, например, по вот этому учебному пособию. Как минимум, нужно усвоить команды перехода по каталогам и способы запуска программ и скриптов.

Если Вы пришли в мир Mac OS из мира Linux’а и FreeBSD, то, скорее всего, знаете как минимум основы shell-скриптинга. Но и для вас в статье может оказаться кое-что интересное, ведь в маке есть уникальные консольные команды, которые так же полезно знать.

Читайте также:  Eclipse stm32 mac os

Вот о некоторых особенностях маковской консоли далее и пойдёт речь.

Начнём работу


Для начала избавимся от стандартного терминала. Ну, точнее, поставим другой — получше. Я лично предпочитаю 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.

Читайте также:  Запретить обновление windows 10 cmd

Есть ещё 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-скриптинг да и вообще в консоль.

Источник

LearnLearn the Mac OS X Command Line

Jim Hoskins
writes on September 27, 2012

This is a command line tutorial primarily conducted in in the OS X command line. Because of OSX’s unix heritage, much of the info here is also useful in other unix inspired systems, like the Linux command line.

The command line can be a scary place when you first encounter it. When you read some instructions that tell you to open up a terminal window and type some cryptic words and phrases, it can seem like you’ve been sucked into the matrix, expected to decrypt an endless stream of indecipherable characters.

Fear not, it’s really not that difficult to use. In fact, when you see an experienced user looking at a terminal that is scrolling line after line of text faster than you can even read it, they aren’t really reading it either. For the most part they may be scanning for some key words, but mostly they are just waiting for it to stop.

Check out our full library of learning courses.

How to use Terminal to open the command line

Before you can use it, you need to be able to find it.

So what we need to do is open the terminal. On OS X, open your Applications folder, then open the Utilities folder. Open the Terminal application. You may want to add this to your dock. I like to launch terminal by using Spotlight search in OS X, searching for “terminal”.

Anatomy of the Console

First let’s clarify a few terms.

Console: This is the system as a whole. This is both the command line as well as the output from previous commands.

Command Line: This is the actual line in a console where you type your command.

Prompt: This is the beginning of the command line. It usually provides some contextual information like who you are, where you are and other useful info. It typically ends in a $ . After the prompt is where you will be typing commands.

Terminal: This is the actual interface to the console. The program we use to interact with the console is actually a “terminal emulator”, providing us the experience of typing into an old school terminal from the convenience of our modern graphical operating system.

Читайте также:  Образ загрузочного диска windows для флешки

Use CLI to run a command

Nearly all commands follow a common pattern with 3 main parts. The program, the options, and the arguments. Let’s see an example.

Type the code above. Do not type the leading $ . This is a common convention used is denote what follows is a command to be run. Once you have typed it out, hit enter to run it, and see what happens.

The program is the verb. It describes what you want to do. In our example ls is the program. ls is short for list, meaning, I want to see a list of files somewhere on my computer.

Options are like the adverb. They usually modify the way the program will run. In our example -l is an option. It’s short for “long”. Without this option, the list will be simply the filenames. When we modify the command with -l , it will display to us the files along with more detailed information. Options are just that: Optional. Any command should have some default behavior when called without options. Each command has it’s own options. Most often the order of the options do not matter, but occasionally they may.

The arguments are what’s left. In our case the

.These are the objects of our sentence. They describe what we want our command to act on. In our example the

is a shorthand name for a special folder on your computer: your home folder. So we are saying we want to list all of our files in our home folder. Some programs may not need arguments. For instance, without arguments, ls will list the files in the directory you are currently in. More on that later. Again, each program has different arguments, and the order of the arguments typically matter.

Where Are You?

In the console, you are always working in a directory, or folder, on your computer. We call this your working directory. You can see where you are using pwd (short for print working directory)

This command will print out your current location. You can change your directory with cd (short for change directory). If you pass it an argument, it will change your to that location, if it exists. Without an argument, it will take you to your home directory (

You’ll notice that I just passed it a directory named Documents, because I was in my home directory, that contains a directory called Documents. This is relative path, because I specified my destination relative to my current directory. I can provide an absolute path by providing the full path beginning with the / , or starting with my home directory (

If you want to navigate “up”, that is to the directory that contains your current directory, you can use the special name .. which you can even use separated by slashes to navigate several levels up.

From my Documents directory, this command will take me up to my home directory.

Get Some Help, man!

Even when you learn what commands you can use, there is still a lot of power in each command or program. There are often dozens of available options, and depending on your arguments, your command could behave in several different ways.

Fortunately, most commands have a manual. To read, use the man command. Pass the name of the command you want to learn about as it’s only argument. For instance to learn more about ls , run

The manual can be scrolled with the arrow keys or space bar. Pressing q will quit.

Want to know more about man? Run man man

Some more commands.

There are a ton of different commands you can use, but only a couple dozen will get you pretty effective in the command line.

We learned about ls , pwd , cd , and man .

Try using the man command to learn about these commands

  • mkdir Make a new directory
  • touch Make a new empty file
  • cp Copy a file
  • mv Move a file
  • rm Remove a file or directory (learn about the -r option)
  • less Show the contents of a file in a scrolling buffer

If you’re looking to take your programming to another level, check out our Techdegrees. Our faculty of tech professionals guide learners like you from mastering the fundamentals of coding to polishing the portfolio and skills of a job-ready software developer. Try one of them out with a free seven-day trial today.

Источник

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