LearnIntroduction to 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 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.
Running 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.
Основы работы с командной строкой (Терминалом) на Mac OS X
- написана командой Vertex Academy. Надеемся, что она Вам будет полезна. Приятного прочтения!
- это одна из статей из нашего «Самоучителя по Java»
Привет! Это статья для тех, кто только начинает знакомство с командной строкой.
Сегодня мы рассмотрим основные команды в среде MacOS.
Где найти командную строку
Есть несколько способов:
- Вызовите окно поиска (Cmd + Пробел, на Вашем устройстве может быть установлена другая комбинация), и напишите «Терминал» или «Terminal»:
- Другой вариант — найти Терминал в Launchpad:
Там, в папке «Другие», можно найти значок Терминала:
Теперь, если мы нажмем на значок, откроется такое окно:
Обратите внимание: это стандартная программа для работы в командной строке. При желании, Вы можете установить и какую-нибудь другую программу — например, iTerm, Terminator и т.д.
Основные команды:
Давайте рассмотрим каждую из них по отдельности.
Команда ls
ls — расшифровывает как «List files in the directory», что переводится как «перечислить все файлы в папке» или «вывести на экран список файлов в папке». Синтаксис команды такой:
Итак, если Вы только открыли терминал, Вы автоматически попадете в так называемый «home directory» — «исходный каталог», или «хомяк» — сленг от слова»home» 🙂 Обычно это папка, которая называется так же как и имя пользователя. Давайте откроем терминал и напишем команду ls:
Если нажать Enter, то мы увидим:
У Вас исходный каталог может выглядеть по-другому — например, у Вас не будет папок 42FileChecker, если у Вас не будет установлен Adobe Creative Cloud, — не будет папки Creative Cloud Files, и т.д.
Команда cd
cd — расшифровывается как «Change directory», что переводится как «сменить папку» или «перейти в другую папку». Синтаксис такой:
Например, как Вы помните, мы только открыли терминал и сейчас находимся в home directory:
Мы можем зайти в одну из этих папок. Давайте, например зайдем в папку Desktop (Рабочий стол). Для этого, напишем:
cd Desktop
Если мы нажмем Enter, мы перейдем на Рабочий стол. Сейчас, у нас на Рабочем столе находится только папка «Files»:
И если мы теперь вызовем команду ls, увидим только папку Files — то же самое, что видим на своем Рабочем столе:
Чтобы выйти обратно, напишем:
То-есть мы пишем «cd«, а потом две точки:
Нажмем Enter. Теперь, давайте еще раз вызовем ls:
Как видите, мы опять находимся в home directory.
Команда pwd
pwd — расшифровывает как «Present working directory», что переводится как «текущая рабочая директория». То есть команда pwd показывает, в какой сейчас папке мы находимся. Синтаксис такой:
Например, у нас имя пользователя «Maria». Поэтому, наша домашняя папка так и называется:
Опять же, если мы зайдем в папку Desktop:
Если мы сейчас напишем pwd, то увидим, что мы находимся папке «Desktop«:
Команда mkdir
mkdir — расшифровывается как «Make directory», что переводится как «создать папку». Синтаксис такой:
mkdir
Например, сейчас мы находимся на Рабочем столе. Как Вы помните, в этой папке у нас только одна папка — Files:
Теперь, давайте создадим новую папку — например, с названием «NewDirectory»:
Теперь, если мы вызовем команду «ls», то увидим, что у нас уже две папки:
Для большей наглядности, мы можем открыть папку в Finder:
Команда open
«Open» переводится как «открыть». С помощью этой команды мы можем открыть что угодно — папку или файл. Синтаксис такой:
open
Например, сейчас мы находимся в папке Desktop. Давайте откроем папку NewDirectory. Для этого мы пишем:
open NewDirectory
Нажмем Enter. Тогда мы увидим, что откроется папка «NewDirectory» в Finder:
Чтобы открыть текущую папку, мы пишем:
open .
Здесь точка означает папку, в которой мы находимся. Например, давайте вернемся в папку home directory:
Теперь, мы находимся в папку, которая называется именем пользователя:
Напишем «open .«:
Отлично! Точно так же мы можем открывать и файлы. Например, создадим новый текстовый файл на Рабочем столе:
Теперь, зайдем на Рабочий стол:
open text.txt
Тогда, файл будет открыть в программе по умолчанию:
Мы можем открыть этот же файл и находясь в другой папке. Например, вернемся в «домашнюю» папку. Это, кстати, можно сделать, если просто написать «cd«, без аргументов:
Теперь, мы будем находиться в папке с именем пользователя:
Давайте откроем файл text.txt отсюда. Напишем путь к файлу:
open Desktop/text.txt
Получим такой же результат, как и в первый раз:
Точно так же, мы можем открыть файл и если он находится в папке «выше». Например, зайдем в папку NewDirectory:
Мы можем открыть файл, если напишем следующее:
open ../text.txt
Увидим, что файл, как и раньше, открылся в программе TextEdit:
Но мы и сами можем выбрать приложение, в котором следует открыть файл. Синтаксис такой:
open -a
Например, давайте откроем файл с помощью приложения Safari. Пишем:
open -a Safari ../text.txt
Если нажать Enter , увидим что файл открылся в браузере:
Команда touch
С английского «touch» переводится как «прикоснуться», «потрогать» 🙂 Эта команда позволяемое нам создать пустой файл. Синтаксис такой:
touch
Например, сейчас мы находимся в NewDirectory на Рабочем столе. Мы можем проверить это с помощью команды pwd, которую мы выучили раньше:
Теперь, давайте создадим файл. Мы можем сделать что угодно — изображение (img.jpg), текстовый файл (file.txt) или звуковой файл (sound.waw). Естественно, все эти файлы будут пустыми.
touch image.jpg
Теперь, в папке NewDirectory появится файл image.jpg. Давайте откроем папку с помощью команды open и посмотрим:
Отлично! Еще, мы можем создать несколько файлов одной командой. Их имена можно указать через пробел:
touch file1 file2 file3 .
Например, давайте сделаем несколько файлов с расширением .txt. Напишем в командной строке:
touch 1.txt 2.txt 3.txt
Теперь, если мы откроем папку NewDirectory, мы увидим наши новые файлы:
Команда mv
mv — расфшифровывается как»Move», что переводится как «переместить», «передвинуть». С помощью этой команды мы можем:
- переместить файл из одной папки в другую
- переименовать файл
Итак, чтобы переместить файлы из одной папки в другую, мы пишем следующее:
Например, давайте переместим файл image.jpg из папки NewDirectory на Рабочий стол (т.е. на уровень выше). Для этого, пишем:
mv image.jpg /Users/Maria/Desktop
Как видите, мы указали абсолютный путь. То-есть это путь не относительно нашей текущей папки («относительный» путь), а путь по которому папка находится в системе. Это можно сравнить с адресом. Можно сказать, что дом находится «на соседней улице» (это будет относительный путь), а можно что он находится по адресу. например, Ул. Уличная 123 (это будет абсолютный путь).
Таким образом, наш файл переместиться на Рабочий стол:
Как видите, теперь в папке нет изображения. Вместо этого, оно находится на Рабочем столе:
Давайте теперь вернем файл обратно. Напишем:
mv ../image.jpg .
Как видите, мы берем файл image.jpg, который находится на уровень выше (../image.jpg), и переедаем его в папку, в которой мы находимся сейчас (.).
Теперь, файл image.jpg опять в папке NewDirectory:
Кроме того, мы можем перемещать несколько файлов одновременно. Синтаксис такой:
mv file1 file2 file3.
Итак, давайте переместим все файлы из папки NewDirectory на Рабочий стол. И в этот раз, мы используем не абсолютный путь, а относительный. Пишем следующее:
mv image.jpg 1.txt 2.txt 3.txt ./..
Точно так же, мы могли бы написать:
mv * ./..
где * означает все файлы в папке.
Вот теперь мы можем увидеть, что все указанные нами файлы переместились на Рабочий стол:
Теперь, давайте посмотрим как можно переименовать файл. Синтаксис такой:
Например, давайте поменяем название файла с image.jpg на picture.jpg. Для этого нам нужно перейти в папку Рабочий стол с помощью команды cd, а потом написать:
mv image.jpg picture.jpg
Если мы теперь откроем папку Рабочий стол, то увидим следующее:
Отлично! Теперь файл называется по-другому — picture.jpg.
Вот и все — теперь Вы знаете основные команды для работы с командной строкой на Mac OS.
Спасибо, что были с нами! 🙂
Надеемся, что наша статья была Вам полезна. Можно записаться к нам на курсы по Java на сайте.