Mac OSX Terminal (command-line tips and tricks)
This tutorial describes how to make use of the macOS Terminal to make your life easier and less frustrating.
What Apple calls the Terminal is what Linux people call the shell console (more specifically, the Bash shell). It’s also called a command-line terminal, abbreviated as CLI.
Information here is often used in interview questions.
Open Terminal (several ways)
On the Mac, the Terminal app is kinda buried, probably perhaps because those who use a MacOS laptop just for social media probably won’t need a Terminal.
But if you’re a developer, it’s hard to get away from using a CLI.
There are different ways to open a Terminal command line.
My preferrence is a way that doesn’t require reaching for a mouse and using the least number of keystrokes:
- Press command+space keys (at the same time) to bring up Apple’s Spotlight universial search, then
- Type “termin” so “Terminal.app” appears.
- Press the space bar to select it.
Alternately, if you prefer moving your mouse:
- Click the Finder icon on the app bar.
- Click Applications on the left pane.
- Click Utilities.
- Click Terminal.
PROTIP: If you are at the Finder program (since Yosemite) you can open a Terminal to a folder listed within Finder by pointing your mouse on it, then tapping with two fingers on the touchpad/mousepad. To enable that:
- Click the Apple icon, System Preferences.
- Press K and select Keyboard.
- Click Shortcuts, Services.
- Scroll to the Files and Folders section.
- Check on New Terminal at Folder.
- Close the dialog by clicking the red dot at the upper left corner.
Bash shell invocations
I put in an echo in the various files that macOS executes upon user login, when a new terminal is opened, and when a bash shell is invoked:
When macOS logs in a user, it executes file /etc/profile. That file’s code:
echo $ resolves to /usr/local/bin/bash.
The /etc/bashrc file contains:
The above defines the $PS1 variable which sets the Terminal’s prompt to the left of the cursor.
NOTE: On Ubuntu, instead of /etc/bashrc, the file is /etc/bash.bashrc.
RedHat also executes /etc/profile.d if the shell invoked is an “Interactive Shell” (aka Login Shell) where a user can interact with the shell, i.e. your Terminal bash prompt.
Thus, whatever is specified in /etc/profile is NOT invoked for “non-interactive” shells invoked when a user cannot manually interact with it, i.e. a Bash script execution.
PROTIP: One can change those files, but since operating system version upgrades can replace them without notice, it’s better to create a file that is not supplied by the vendor, and within each user’s $HOME folder:
In other words, file /etc/profile is the system wide version of
/.bash_profile for all users.
Examples of custom settings include:
export HISTSIZE=1000 # sets the size of .bash_history lines of command history (500 by default)
User Mask for permissions
Wikipedia says umask controls how file permissions are set for newly created files. Please read it for the whole story on this.
To identify the User Mask for permissions:
Since the default is “0022”: -S shows the symbolic equivalent to “0022” for u=user, g=group, o=others :
r is for readable, x is for eXecutable by the user.
To set the User Mask for permissions:
Within Text Editors/IDEs
Many prefer the terminals built into VS Code and other editors/IDEs.
Text wrapping
This page contains notes for system administrators and developers, who need to control Macs below the UI level, which require typing commands into a command-line terminal screen.
- To avoid text wrapping, cursor on the right edge to expand the screen width.
Hyper terminal app
Get the .dmg installer from the website https://hyper.is. It’s used by tutorials author Wes Bos.
Unlike Apple’s Terminal, which is closed-source, Hyper is an open-source and extensible terminal emulator. It is available on MacOS, Windows, and Linux because it’s built using Electron (the same platform that powers Atom, Slack, and Brave). So it can be slow.
To customize Hyper, add the name of many packages to its config file
iTerm2 for split pane
Many prefer to install and use iTerm2 instead of the built-in Terminal program. Install iTerm2 using Homebrew:
Terminal does not support but iTerm2 does support dividing the CLI into several rectangular “panes”, each of which is a different terminal session:
- split window vertically with Command+D
- split window horizontally with Command+Shift+D
- Navigate among panes with command-opt-arrow or cmd+[ and cmd+]
- Temporarily toggle maximize the current pane (hiding all others) with command-shift-enter
- Exit out a pane by typing exit in that pane
Pressing the shortcut again restores the hidden panes.
On Linux, there is the screen command.
See Iterm2 Cheat Sheet of iTerm2 keyboard shortcuts. https://github.com/nobitagit/iterm-cheat-sheet/blob/master/README.md
Alphabetical Commands list
A list of all commands native to macOS is listed alphabetically at https://ss64.com/osx.
To exit from the Terminal shell:
Get back in for the remainder of this tutorial.
Shutdown
CAUTION: To kill all apps and shutdown a Mac right away (with no warning and no dialog):
sudo shutdown -h now
Text Command Line Bash Shortcuts
These come from the bash terminal on Linux machines here: Press control with your pinkie, then …
- control + C = Close processing
- control + L = cLear screen
Environment Variables
A big reason to use a command-line terminal is to set environment variables.
Like on PCs, the PATH system environment variable stores where the operating system should look to find a particular program to execute.
To see what is already defined:
The listing such as this, which declares the “XPC_FLAGS” system variable:
declare -x XPC_FLAGS=”0x0”
This talks about setting launchd.conf and rebooting. This applies to all users.
To see what is defined:
PROTIP: $PATH must be upper case.
The response I’m getting includes:
Notice colon (:) separator used in Mac and Linux vs. semicolons used in Windows PATH.
Default editor
The command to invoke the default editor is defined by a variable:
By default, it’s TextMate:
If you want to change it to nano or other editor, see My tutorial on text editors.
On Terminal session, copy what has been typed and open the default text editor so you can edit the command:
Alternately, (which also works in Linux) while holding down the control key, press X and E together:
control + X + E
Make changes, then copy all, switch or exit to the Terminal, then paste.
Switch among programs
To switch among programs already running in macOS, hold down the command key while pressing tab multiple times until the program you want is highlighted (with its name) in the pop-up list. This is equivalent to the Windows control+Esc key combo.
Command history
List previous command history:
This is the same as:
PROTIP: History does not display commands entered with a leading space.
Cursor up and press Enter to re-execute.
Press control + R to begins a “reverse incremental search” through your command history, then type, it retrieves the most recent command that contains all the text you enter. Much better than something like:
Press control + S to reverse the mode.
The clear command does not clear history.
Clear the terminal history:
clear
Foreground processes and background jobs
List the first process (with Parent process ID of 0) launched (into user space) at boot by the system kernel:
f adds columns for status of the command (CMD) to invoke the process:
By contrast, on Linux system, the first CMD is /lib/systemd/systemd.
To list all processes, don’t specify 1
PID given process name
To list the process ID given a process name such as “firefox”:
This can be generalized in a shell program containing:
Alternately, Linux has a command which returns the PID associated with a process name. But it’s not avaiable on macOS, so:
To emulate a long-running process in the foreground:
No additional commands can be accepted.
To kill the current process, press control + C.
background jobs
Run a program in the background with the &:
List jobs (processes) running in the background:
Suspend control+Z
To suspend the process, press control + Z. The response is like:
Internally, this sends a “20) SIGTSTP” signal to the process.
To have the process continue (internally sending a “18) SIGCONT”:
Copy the PID (Process Identifier) number for use in the kill command, such as:
There are many ways to kill a process:
To kill a specific process, ee need to specify its PID (Process Identifier):
Some applications are written to receive a sigterm so that it can take steps to gracefully cleanup and exit.
The key ones, in order of aggressiveness:
kill 289 # sends sigterm
kill -15 289 # sends sigterm
kill -2 289 # sends sigint
kill -1 289 # sends sighup
kill -9 289 # sends sigkill signal to the kernel without notifying the app, a “dirty shutdown” used when the app is misbehaving.
List open files
To list process id’s and port (such as 8080), use the “list open files” command:
PROTIP: Use grep to filter because the response is usually too many lines.
(You’ll need to provide your password).
The right-most column heading «NAME» shows the port (either TCP or UDP).
Folders accessed by developers
In Finder, select from the left panel the first item under the Devices list.
Click on Macintosh HD.
- Applications hold apps installed.
- Incompatible Software hold apps which cannot be installed, such as Amazon Kindle, which competes with Apple’s iBooks. This occured during upgrade to Yosemite.
- Library/Library holds Apple internal apps.
- System hold apps installed.
- Users hold data for each user defined, as well as a Shared folder accessible by all users.
Click on your username (wilsonmar in my case).
This action is the same as clicking on the last default item under the Favorites list.
Many WordPress developers prefer to add a folder named Sites which holds the wordpress folder expanded from download.
vs. /etc in Linux
VIDEO: On both Mac and Linux, the “et-see” folder contains system and program configuration files, for both default system and programs you install (such as “teamviewer”, etc.)
/bin contains system
/sbin are for system administrators such as ping, fdisk, mount, umount, etc.
Terminal File Listing Home Folder
By default, the Terminal shows the hard drive and lowest level file folder name, in white letters over black.
To show the present (current) working directory (folder):
The response for me is:
You will of course have a different machine user name than wilsonmar.
Note the pwd command is built internally to the Bash shell:
pwd is a shell builtin
To get back to the home folder:
Alternately, use the $OLDPWD environment variable that MacOS automatically maintains to remember the previous working directory so that you can switch back to it:
List files and folders
List all file names (without any metadata):
Folders available by default include Documents, Downloads, Pictures, Desktop, Music, Movies.
Note the ls command is an external command added to the Bash shell:
The response lists where ls is defined:
ls is hashed (/bin/ls)
Dive into a folder type:
Nothing happens because upper case letters are important.
Press delete to remove the mu and type:
Press Enter for the Music folder.
Go back up a level:
Create a Projects folder to hold projects downloaded from Github:
-p specifies creating the parent folder if it doesn’t exist.
This only needs to be done once.
List files and folders
List all files with their permission settings:
Notice that no hidden files are listed.
List all hidden files with permission settings, piping the listing to more instead of having results flying by:
A colon appears at the bottom if there is more to show.
Cancel the listing, press control + C.
Notice the .bashrc on the first page, something like:
If a file is not listed, create it with:
To make it rw r r:
List only hidden files in the current folder:
Show Hidden Invisible Files in Finder
By default, the Mac’s Finder does not show hidden files.
Close all Finder folders.
Enter this in Terminal before typing Return:
This causes all Finder windows to be reset.
To make invisible files visible again:
A description of each keyword:
defaults — OSX’s command to change defaults, apple’s low-level preference system.
write — tells defaults you want to change a preference, or write it
com.apple.finder — defaults that the application’s preferences you want to change is Finder, specified by the application’s bundle identifier.
AppleShowAllFiles — specifies which preference you want to change within the application.
TRUE or FALSE — the value you want to set the preference to. In this case, it is a boolean, so the values must be TRUE or FALSE. I think you might be able to use YES or NO, but I’m not sure.
&& — a terminal operator to run whatever’s after this if the command to its left is successful.
killall — kills processes or closes applications.
Finder — specifies the process or application to close.
For more on this, see this.
Create Terminal Aliases
Wireless up and down
Most developers leave files un-hidden.
To set wireless (device en0 ) up or down without clicking on the icon at the top:
ifconfig en0 down
This command requires sudo permissions.
Set alias command to just type showFiles and hideFiles to show and hide Mac OS X’s hidden files, consider this article to create such terminal aliases in the
tree alias or brew install
OSX does not come with the tree command that many other Linux distributions provide. So add it using:
If you don’t want to install a program, add an alias for a tree command by adding this in the
Alternately, add it by installing a command using brew:
Active Terminal sessions need to be closed so new Terminal | Shell | New Window | Shell has this activated.
See list of parameters:
List only 2 levels deep with human-readable file size kilobytes and sort by last modified date:
Cursor to Screen Hot Corners
By default, if you move the mouse to one of the corners of the screen, stuff happens. It can be annoying.
- Click the Apple menu at the upper left corner.
- Select System Preferences.
- Select Desktop & Screen Saver.
- Select the “Screen Saver” tab.
- Click “Hot Corners” at the lower-right corner.
Select actions for each of the corners.

PROTIP: Disable each by selecting the dash (last choice) so they don’t show up when you’re just trying to navigate to something near the edge.
Press Esc to bring the screen back.
PROTIP: NOT having a quick way to “Put display to sleep” is considered a security vulnerability by CIS. The lower-left corner is less popular location on Mac than Windows.
Hosts file
Mac, Windows, and Linux systems have a hosts file that locally does the work of the public DNS – translating host names (typed on browser address field) to IP address numbers.
Show text file contents to the Terminal console:
The default contents:
PROTIP: fe80:: is a block of IPV6 addresses reserved for link-local addresses used for packets sent only to directly connected devices (not routed). The network discovery protocol (NDP), which replaces ARP and DHCP in IPv4, is the biggest user of link-local addresses (NDP sorta .
fe80::1 is like 127.0.0.1 for IPV4, but actually IP address 169.254.. in IPV4, an address not often used.
Each IPV6 interface has a different link-local address starting with fe80:: and (typically) ending with a modified version the interface’s MAC address (EUI-64 format) to ensure a unique address on a segment.
Programs such as OpenVPN add to the bottom of the file:
BLAH: The Linux tac command to list backward is not in Mac:
Show a file in -reverse (bottom-up):
Change n2 to a different number of lines to show.
PROTIP: This command is useful to see the lastest entries appended to the end of a large log file.
Expose spaces at end of lines by showing at end of every line $ end-of-line characters that are otherwise not shown. For example, in a file on every macOS:
Edit the hosts file on a Mac using the Atom text editor:
Terminal Ping Host
Find the IP address of a website host name:
SSH tunnel
To access a remote server through a port that is not open to the public:
VIDEO: Bind local port 3337 to remote host 127.0.0.1 port 6379 using user root in emkc.org
BTW 6379 is the default port for a Redis instance.
DNS Configuration with NameBench
Analysis at one time showed this ranking by speed:
- UltraDNS at 156.154.70.1
- Google at 8.8.4.4, 8.8.8.8
- OpenDNS at 208.67.222.222, 208.67.220.220, 208.67.222.220
Google Namebench tries the speed of various DNS servers from YOUR machine (which takes some time) and pops up in your browser this:
- If you don’t see the Apple icon at the top of the screen, move the cursor to the very top of the screen for a few seconds.
- Click on the Apple icon at the upper left corner.
- Select System Preferences.
- Click Network.
- Click Advanced.
- Click DNS.
- Click [+], copy, and paste
- 205.171.3.65
- 216.146.35.35
- 192.168.0.1
Clear DNS Cache
Flush the DNS cache (since OSX 10.9):
sudo dscacheutil -flushcache
dscacheutil is the Directory Service cache utility used to Gather information, statistics, initiate queries, flush the cache:
BTW, the equivalent for Ubuntu is
sudo service network-manager restart while other Linux flavors uses
sudo /etc/init.d/nscd restart .
Windows uses
ipconfig /flushdns .
Different commands are needed for different versions of OS. OSX 10.10 added requirement for sudo when using the built-in discoveryutil:
sudo discoveryutil udnsflushcaches
Bash Profile Configuration
The profile file is run during boot-up to configure the terminal to define file path, shims, and autocompletion handlers.
This is the single biggest frustration with people using Linux on Mac.
One of the earliest articles on bash here shows shell variables, environment variables, and aliases.
Each operating system has its own file name for its profile:
-
With Ubuntu: Modify
/.profile instead of
/.zshrc file instead of
PROTIP: If there is both a .bash_profile and a .profile file, boot-up only executes the first one it finds.
On my Yosemite Mac, open a terminal and:
View the file using the vi editor that comes with OSX:
According to the bash man page, .bash_profile is executed during login before the command prompt, while .bashrc is executed for interactive non-login shells such as when you start a new bash instance by typing /bin/bash in a terminal.
Here’s what my profile file begins:
Exit vi by typing :q
Some installers request that adding a $PATH using a command such as:
To execute profile with the changes:
Alternately, to install GHC copy and paste into
To run a Bash script while avoiding the confirmation prompt:
set -- -f; source bootstrap.sh
Operating System Kernel
I can use Linux commands in my version of the operating system:
uname -a (a for all) or uname -rvm
14.3.0 Darwin Kernel Version 14.3.0: Mon Mar 23 11:59:05 PDT 2015; root:xnu-2782.20.48
which is a combination of:
uname -r for release number,
uname -v for kernel version,
uname -m for model:
x86_64 for Intel or AMD 64-bit or
i*86 for 32-bit.
For more information about Darwin operating system developed at Apple, see:
- http://www.wikiwand.com/en/XNU and
- https://www.wikiwand.com/en/Comparison_of_operating_system_kernels
NOTE: lsb_release -a which works on Debian, RHEL 6.6, and Ubuntu is not recognized on Gentoo nor CentOS 6, which has no folder /etc/lsb-release.
See Distrowatch.com, which details each release of various Linux distributions (RedHat, etc.).
Setup Your Mac Like a Pro
Paul Irish is one of top pros among developers, and now a Google Evangelist. He put his Mac configuration settings on github.com/paulirish/dotfiles. But he recommends cloning github.com/mathiasbynens/dotfiles/.
On the Git page notice that he has established an industry convention of using Projects folder we defined earlier.
On the Git page I clicked on Clone in Desktop.
The library is called dotfiles because that’s what hidden files are called, and most configuration files are hidden.
PS1 terminal prompt setting
The PS1 variable defines how to display the prompt.
Paul Irish offers his setup-a-new-machine.sh at https://github.com/paulirish/dotfiles
ZShell (included with Mac and can be set as the default in Terminal)
- oh-my-zsh as a ZShell framework
- The oh-my-zsh Git plugin
- The oh-my-zsh theme called jnrowe
By default, if you have a long file name, it would leave little room to type in commands before it wraps to the next line.
To redefine what appears in the prompt, edit this file using the vi editor that comes with each Mac:
Copy this and paste to the bottom of the .bashrc file:
The command above uses global parameters $USER and $PWD, plus colors from this list.
Root user for sudo commands
If you try a command that responds about “permissions denied”, you need to execute as a root user.
The root user has the ability to relocate or remove required system files and to introduce new files in locations that are protected from other users. A root user has the ability to access other users’ files.
Any user with an administrator account can become the root user or reset the root password.
Under a *nix system like MacOS you must have “root” (administrative) privileges to start IP-services using ports smaller than 1024.
After MacOS install, the root or superuser account is not enabled. While it is possible to enable the root account, once enabled, if forgetten, you’ll have to reboot from the installer drive (a hassle).
The easiest way it to have the last command (in history) automatically retrieved so you don’t have to retype it to
execute again under root:
It is safer and easier to use the sudo command to gain temporary root access to the system rather than logging out and logging in using root credentials.
Alternately, this command only reads the $SHELL variable and executes the content:
sudo -s
You would be prompted for a password.
- To determine whether you’re in sudo:
whoami
The response “root” says you’re still in sudo rather than your user name.
- To demote out of root:
PROTIP: There are several ways to invoke sudo *
This command is my preferred way to get into root for awhile because it keeps the environment variables intact:
sudo /bin/bash
The command above uses a non-login shell, and reads just the .bashrc of the calling user. Not all dot-files are executed.
If you want environment variables specific to root and be in the root home directory (rather than your user’s $HOME directory), this command executes \/etc/profile, .profile, and .bashrc which defines them:
sudo su -s
If you switch between Zsh and Bash, this command runs the shell specified by the password database entry of the target user as a login shell:
sudo -i
If you switch between Zsh and Bash, this command runs the shell specified by the password database entry of the target user as the login shell, then executes login-specific resource files .profile, .bashrc (or .login):
sudo -s
NOTE: The folders that bash looks into are in bin:
On a fresh Yosemite, that would contain:
Each additional app adds to the front of the list:
Separating the folders between colon separator:
- /Library/Frameworks/Python.framework/Versions/3.4/bin
- /opt/local/bin
- /opt/local/sbin
- /Applications/MAMP/bin/php5/bin
- /Applications/MAMP/Library/bin
- /Applications/Adobe AIR SDK/bin
- /usr/local/bin
- /usr/bin
- /bin
- /usr/sbin
- /sbin
New folders are added to the front of the PATH using a command such as:
export PATH=<new folders>:$PATH
Depending on how you’re setup, file
/.bash_login contains the path echo’d.
Or your PATH may be set in /etc/profile for all users
Create Windows-like shortcuts with parameters using text editor
Mac OSX doesn’t allow you to create shortcuts like Windows. OSX alias don’t allow parameters (ex. create a Screen Sharing shortcut that connects to a specific computer).
Jessie suggests this to create a Windows like shortcut with parameters in the Comments field.
Another alternative is to use a text editor to create URL shortcut files like the ones Windows Internet Explorer stores its bookmarks. Apple Safari recognizes them when clicked within Finder. So they are cross-platform.
- Copy the URL to the clipboard by pressing Command+C.
- From within a text editor, open a new text file.
- Type at the top of the file: [InternetShortcut]
URL= - Paste from clipboard by pressing Command+V
- Press enter/return to add a blank line under the URL line.
- Save the file with a .url file extension.
- From within Finder, click on the file to see it display by Safari.
Mount .dmg files using hdiutil tool
Mount a .dmg (Disk Image) file (substituting for /path/to/diskimage):
The response is like:
Note the disk from the message above to unmount (detatch):
The same utility can mount .iso images:
IPv6 compatibility with Curl command line apps
curl http://localhost:3000
Previously, when invoked on Mac OS 10.10 (Yosemite), you needed to add a parameter to make the request use IPv4:
curl http://localhost:3000 –ipv4
Otherwise, even if the URL loads fine in a browser, you will see an error message such as:
curl: (7) Failed to connect to localhost port 3000: Connection refused
This occurs because curl, under Yosemite, uses IPv6 by default but some apps, such as LoopBack.io, by default uses IP v4.
See if you see IP v6 entries in your hosts file (::1 localhost, fe80::1%lo0 localhost). If they are there it is likely that curl is making requests using IP v6.
You can make your LoopBack app use IPv6 by specifying an IPv6 address as shown below:
Largest files taking up disk space
Linux has a ncdu (NCurses Disk Usage) utility to list files in order of how much space they occupied.
It’s not in macOS by default, so:
Now list files within a folder by space used:
The command takes up the whole screen (like top), so press control+C to exit.
To get the directory utilitization size of the current directory:
The response is like:
The dot means the current folder.
You can specify a sub-folder named, for example, “code”:
Empty Trash
When files or folders are moved to Trash, they are sent to folder
Count the number files in the folder by piping to the “word count” utility:
(The -al includes hidden files and folders)
(The find . includes files nested within folders as well)
The above command is aliased as cf in my
To recover disk space taken up by files which have been moved to Trash, there are several ways:

Switch to the Finder and click the Finder menu to expose the menu:
You can click on “Empty Trash” or press the Keyboard sequence shift + command + delete.
If you rather not use a mouse within Finder, switch to Terminal and type this AppleScript command (which will take a while to run if there are a lot of files):
NOTE: How to put the above command is aliased as empty in my
Ulimit Too Many Files
By default, operating systems limit how many file descriptors to allow. Each operating system version has a different approach.
Linux operating systems have this command:
ulimit -a
On my Sierra the response was:
Check how many file descriptors you have:
launchctl limit maxfiles
On Sierra the response was:
The first number is the “soft” number, the second one is the “hard” number.
After fixing, the numbers I now see are:
Such numbers were set with a command such as:
sudo launchctl limit maxfiles 10240 10240
The maximum setting is 12288?
NOTE: To change maxfiles on Sierra, define a plist. TODO: verify
Due to security, OSX Lion removed the “unlimited” option and now requires a number to be specified.
PROTIP: launchctl is a rough equivalent to the systemctl command used in Linux systems. launchctl interfaces with launchd to load, unload daemons/agents and generally control launchd.
Disable System Integrity Protection
Some programs make calls to the operating system which OSX began to see as a threat, beginning with El Capitan.
Apple says System Integrity Protection blocks code injection (and many other things).
But what about useful programs (such as XtraFinder) which works by injecting its code into Finder and other application processes?
- For example, OpenVPN issues a JSONDialog Error “DynamicClientBase: JSONDialog: Error running jsondialog”.
To get around this, you need to partially disable System Integrity Protection in OS X El Capitan. See Apple’s article on how:
- Run a full backup to an external USB drive.
- Shut down all apps, then the operating system (from the Apple icon).
This is needed because System Integrity Protection settings are stored in NVRAM on each individual Mac. So it can only be modified from the recovery environment running in NVRAM.
When the OS X Utilities screen appears, pull down the Utilities menu at the top of the screen.
Type the following command into the terminal before hitting the return key.
[Mac OS X] Начинающим о работе в Терминале
В OS X обычный пользователь практически не сталкивается с необходимостью использовать командную строку, поскольку большинство его нужд покрывает то, что реализовано в графическом интерфейсе системы.
Другое дело, когда нужны некоторые скрытые возможности, которые недоступны из графического интерфейса. Собственно в этой рубрике мы частенько прибегаем к извлечению этих скрытых возможностей при помощи командной строки. А потому я и решил немного рассказать о программе Терминал и командной строке, а так же дать пару советов новичкам, которые позволят им ощущать себя в ней более комфортно.

Небольшое введение
Начнем с вопроса, что такое Терминал? Прежде всего, это приложение, внутри которого выполняется командный интерпретатор. Его еще часто называют интерфейсом командной строки. Он интерпретирует команды специального языка скриптов.
Пояснение слова скрипт
Правильнее «скрипт» следует называть сценарием, поскольку это одно из значений английского слова — sript. Да и фактически «скрипт» является сценарием. Но термин «скрипт» очень прочно устоялся среди программистов, а потому я немного нарушу правила русского языка и буду называть его именно – скрипт. Тем более что и само слово «сценарий» заимствовано русским языком и родным ему не является.
Языки скриптов бывают разные, но есть наиболее распространенный набор таких языков, а соответственно и их интерпретаторов.
В OS X, по умолчанию используется командный интерпретатор bash . Это улучшенный вариант интерпретатора Bourne shell, который обычно называют просто shell . И он тоже присутствует в нашей системе в виде файла /bin/sh . Правда не используется.
В настоящее время bash – фактически стандарт де-факто в большинстве Unix-подобных систем.
Так же достаточно популярен интерпретатор zsh , который в свою очередь является улучшенным bash (и он тоже есть в нашей системе), но стандартом де-факто он не стал. Возможно пока. Существует и еще целый ряд командных интерпретаторов, не получивших такого большого распространения как bash .
Найти информацию обо всех перечисленных интерпретаторах несложно в «Википедии».
Командная строка
Когда вы запускаете программу Терминал, то видите в ее окне командную строку, которая в моей системе выглядит так:

Командная строка начинается с названия компьютера (у меня он называется iMac), затем следует название текущего каталога — по умолчанию открывается домашний каталог пользователя, который в Unix-системах обозначается знаком
(тильда). Далее следует имя пользователя (в моем случае — gosha ), а за ним знак $ , который называется приглашением – приглашением вводить команды интерпретатору.
Вид командной строки и приглашения можно настраивать, а в минимальном виде это будет просто знак $ . Именно после знака $ и вводятся все команды интерпретатору. Это место обозначает курсор — мигающий прямоугольник (его вид тоже можно настраивать).
Примечание: в заголовке окна Терминала вы видите текущий каталог (в данном случае это домашний каталог, а потому он обозначен домиком), затем имя пользователя, затем название используемого интерпретатора (в данном случае — bash ) и размер окна в символах.
Язык скриптов bash
Командный интерпретатор bash , как я уже написал выше, интерпретирует команды специального языка скриптов. Язык скриптов достаточно несложный язык программирования, который, как и любой язык программирования, предназначен для передачи команд и данных от человека к компьютеру.
Самой простой командой этого языка является запуск программы – она состоит только из имени файла программы и, если необходимо, то и полный путь до этого файла, а так же, возможно, с последующими за именем файла ключами и параметрами, которые дают различные указания выполняемой программе.
Приведу пример. Вы хотите посмотреть содержимое текущего каталога (при запуске Терминала, по умолчанию это будет ваш домашний каталог). Для этого в системе есть программа, находящаяся в файле ls . Ее запуск в командном интерпретаторе заключается во вводе имени файла этой программы и нажатием клавиши Enter:

Небольшое, но важное пояснение
На самом деле, этот файл находится в каталоге /bin и полностью этот файл обозначается как /bin/ls . Но в интерпретаторе есть специальный механизм, позволяющий не вводить полный путь до некоторых файлов программ. Этот инструмент — переменная окружения, которая называется PATH (путь) и содержит список каталогов. Интерпретатор, получив в качестве команды имя файла, указанное ему без пути, просто ищет этот файл в каталогах, перечисленных в переменной окружения PATH . Если находит, то запускает его на выполнение, если не находит, то выводит сообщение — файл не найден.
Посмотреть содержимое переменной PATH вы можете командой:
Естественно эту переменную можно настраивать, но какой-то особой необходимости в этом у обычного пользователя не возникает, а потому я опущу этот вопрос.
Ну а теперь перейдем собственно к советам.
Совет 1 — автодополнение
При использовании командной строки очень часто приходится вводить имена файлов – обычно это файлы различных команд, и вводить имена файлов или каталогов, передаваемых в качестве параметра командам, которые необходимо набирать с указанием полного пути до них. И вот для того, чтобы не ошибиться при наборе, в bash имеется механизм, называемый автодополнением.
Примечание: в дальнейшем, для удобства, я буду называть имя файла команды просто командой. Это общепринятая практика.
Смысл этого механизма заключается в том, что когда вы начинаете набирать команду, вводите первые несколько букв и нажимаете клавишу Tab, в результате чего набор команды будет завершен автоматически. Это же работает и при наборе пути и имен файлов, передаваемых командам в качестве параметров.
Для того, чтобы понять, как это работает, приведу пример. Пусть мы хотим ввести команду diskutil . Начинаем вводить disku и нажимаем клавишу Tab, команда будет дописана автоматически – diskutil . А теперь попробуйте ввести на одну букву меньше — disk и нажать Tab — прозвучит звуковой сигнал и команда дописана не будет. Этот звуковой сигнал предупреждает нас, что есть несколько вариантов команд, начинающихся с букв disk . А вот для просмотра этих вариантов нажмите второй раз клавишу Tab и все эти варианты будут показаны:

Как видно на картинке, имеется шесть команд, название которых начинается с disk , а потому интерпретатор предлагает уточнить следующую букву. В нашем случае нужно ввести букву u , для того, чтобы интерпретатор смог понять, что нам нужна именно команда diskutil , поскольку это единственная команда, начинающаяся с букв disku и затем нажать клавишу Tab. Команда будет дописана полностью.
Попробуйте ввести только буквы di и нажать два раза клавишу Tab. Команд, начинающихся на эти две буквы, будет еще больше. А вот если бы в системе была только одна команда, начинающаяся с букв di , то после первого же нажатия клавиши Tab, она была бы дописана полностью, поскольку интерпретатору не приходилось бы выбирать из разных вариантов.
Точно так же это действует и при наборе имен каталогов и файлов, передаваемых в качестве параметров командам.
Пример. Предположим мы хотим посмотреть содержимое вашего каталога Загрузки при помощи команды ls .
И сразу небольшое отступление.
На самом деле, каталога с названием Загрузки , в вашем домашнем каталоге нет. Это программа Finder, так показывает вам название каталога Downloads . То есть фактически переводит на русский язык слово Downloads . Сделано это для удобства пользователей.
Вы можете убедиться в этом, взглянув на второй сверху снимок экрана, где мы командой ls выводили содержимое домашнего каталога. Как видите, там нет каталога с названием Загрузки , но есть каталог Downloads . Точно так же вы там не увидите каталогов с названиями Библиотеки , Документы , Изображения , Музыка , Общие , Сайты и Фильмы , которые показывает вам программа Finder как перевод с английского на русский названий каталогов: Library , Documents , Pictures , Music , Public , Sites и Movies соответственно.
Итак, вернемся к просмотру содержимого каталога Загрузки (а на самом деле Downloads ) командой ls . Нам нужно ввести название каталога в качестве параметра к этой команде. Набираем ls Dow и нажимаем клавишу Tab, получаем команду ls Downloads , в результате выполнения которой и получим содержимое каталога Загрузки ( Downloads ).
И еще одно отступление.
На самом деле в Unix -системах в этом случае вводят не ls Downloads , а ls ./Downloads . Тем самым обозначая, что каталог Downloads находится в текущем каталоге. Точка — обозначение текущего каталога. Но в реализации bash в OS X , сделано небольшое послабление пользователям и в текущем каталоге, можно ./ опускать, так как будто в переменной окружения PATH прописан текущий каталог, хотя на самом деле его там нет. Вы можете убедиться в этом, выполнив команду echo $PATH . Зачем это было сделано для меня остается загадкой, но таковы реалии OS X. Естественно можно набирать и канонически для Unix-систем – ./Downloads .
Итак, мы ознакомились с автодополнением. Этот инструмент позволяет очень быстро и безошибочно вводить команды. Между прочим, многие файловые операции (копирование, перемещение, переименование, удаление) бывают гораздо проще и их быстрее выполнить именно в командной строке, используя механизм автодополнения.
Совет 2 – история команд
Это еще один механизм, облегчающий работу в командной строке. Дело в том, что интерпретатор bash запоминает все команды, которые вы выполняли. Он сохраняет всю историю команд в скрытом файле вашего домашнего каталога с названием .bash_history . Увидеть этот файл можно при помощи команды ls с ключом -la , т.е. ls -la . Попробуйте.
Пользоваться историей команд очень просто – при помощи клавиш навигации — Стрела вверх и Стрелка вниз. Нажмите первую из них и вы увидите в командной строке предыдущую выполненную команду. Последующие нажатия этой клавиши будут последовательно выводить ранее выполненные вами команды. Соответственно вторая клавиша листает список выполненных команд в обратном направлении.
Это удобно использовать собственно для повторения выполненных команд. Но и очень удобно для их модификации. Например, в моих статьях часто встречаются команды вида defaults write … , которыми мы обычно включаем некоторые скрытые настройки OS X. А отмена включения этих настроек часто делается командой defaults delete … , которую очень просто получить, вызвав из истории предыдущую команду defaults write … и просто исправить ее на соответствующую команду defaults delete… , а не вводить ее с нуля.
Так же, если вы ввели команду с ошибкой и попытались ее выполнить, то после получения сообщения об ошибке, гораздо проще бывает не вводить команду заново, а исправить ошибку в предыдущей, вызвав ее нажатием на клавишу Стрелка вверх, а затем внеся исправления.
Надеюсь, это небольшое введение в основы мира командной строки, не слишком вас утомило.
Основы работы с командной строкой (Терминалом) на Mac OS X

Привет! Это статья для тех, кто только начинает знакомство с командной строкой.
Сегодня мы рассмотрим основные команды в среде MacOS.
Где найти командную строку
Есть несколько способов:
- Вызовите окно поиска (Cmd + Пробел, на Вашем устройстве может быть установлена другая комбинация), и напишите "Терминал" или "Terminal":

- Другой вариант - найти Терминал в Launchpad:

Там, в папке "Другие", можно найти значок Терминала:

Теперь, если мы нажмем на значок, откроется такое окно:

Обратите внимание: это стандартная программа для работы в командной строке. При желании, Вы можете установить и какую-нибудь другую программу - например, iTerm, Terminator и т.д.
Основные команды:
Давайте рассмотрим каждую из них по отдельности.
Команда ls
ls - расшифровывает как "List files in the directory", что переводится как "перечислить все файлы в папке" или "вывести на экран список файлов в папке". Синтаксис команды такой:
ls
Итак, если Вы только открыли терминал, Вы автоматически попадете в так называемый "home directory" - "исходный каталог", или "хомяк" - сленг от слова"home" Обычно это папка, которая называется так же как и имя пользователя. Давайте откроем терминал и напишем команду ls:

Если нажать Enter, то мы увидим:

У Вас исходный каталог может выглядеть по-другому - например, у Вас не будет папок 42FileChecker, если у Вас не будет установлен Adobe Creative Cloud, - не будет папки Creative Cloud Files, и т.д.
Команда cd
cd - расшифровывается как "Change directory", что переводится как "сменить папку" или "перейти в другую папку". Синтаксис такой:
cd <путь к папке>
Например, как Вы помните, мы только открыли терминал и сейчас находимся в home directory:

Мы можем зайти в одну из этих папок. Давайте, например зайдем в папку Desktop (Рабочий стол). Для этого, напишем:
cd Desktop

Если мы нажмем Enter, мы перейдем на Рабочий стол. Сейчас, у нас на Рабочем столе находится только папка "Files":

И если мы теперь вызовем команду ls, увидим только папку Files - то же самое, что видим на своем Рабочем столе:

Чтобы выйти обратно, напишем:
cd ..
То-есть мы пишем "cd", а потом две точки:

Нажмем Enter. Теперь, давайте еще раз вызовем ls:

Как видите, мы опять находимся в home directory.
Команда pwd
- pwd - "present working directory"
pwd - расшифровывает как "Present working directory", что переводится как "текущая рабочая директория". То есть команда pwd показывает, в какой сейчас папке мы находимся. Синтаксис такой:
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", что переводится как "переместить", "передвинуть". С помощью этой команды мы можем:
- переместить файл из одной папки в другую
- переименовать файл
Итак, чтобы переместить файлы из одной папки в другую, мы пишем следующее:
mv <имя файла> <папка>
Например, давайте переместим файл 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 * ./..
где * означает все файлы в папке.
Вот теперь мы можем увидеть, что все указанные нами файлы переместились на Рабочий стол:

Теперь, давайте посмотрим как можно переименовать файл. Синтаксис такой:
mv <старое имя> <новое имя>
Например, давайте поменяем название файла с image.jpg на picture.jpg. Для этого нам нужно перейти в папку Рабочий стол с помощью команды cd, а потом написать:
mv image.jpg picture.jpg

Если мы теперь откроем папку Рабочий стол, то увидим следующее:

Отлично! Теперь файл называется по-другому - picture.jpg.
Вот и все - теперь Вы знаете основные команды для работы с командной строкой на Mac OS.
Спасибо, что были с нами!
Надеемся, что наша статья была Вам полезна. Можно записаться к нам на курсы по Java на сайте.
Как открыть командную строку на Mac

Командная строка — это приложение-переводчик командной строки, доступное как встроенная функция большинства операционных систем. Это по-прежнему предпочтительный способ автоматизации задач или даже настройки функций, доступных только с помощью командной строки. Поскольку это неотъемлемая часть операционной системы компьютера, существует несколько способов получить к ней доступ.
Читайте дальше, чтобы узнать о трех способах доступа к командной строке Mac и некоторых полезных командах.
Использование командной строки на Mac
Версия приложения командной строки для macOS называется Терминалом. Он предлагает доступ к Unix-части macOS, позволяя вам запускать сценарии, редактировать настройки, управлять файлами и использовать текстовые команды. Вы можете запустить Терминал с помощью Spotlight, Launchpad или Finder, и вот как это сделать.
Открыть Терминал с помощью Launchpad
- Перейти в Dock и нажмите на значок серебряной ракеты.

- Выберите “Другое” папку.

- Выберите “Терминал” для запуска командной строки.

Если приложение «Терминал» не находится в папке «Другое», оно может быть где-то еще на панели запуска. Чтобы открыть Терминал, можно попробовать следующие способы.
Открыть Терминал с помощью Spotlight
- Нажмите значок “Spotlight” значок. Это увеличительное стекло в правом верхнем углу. Доступ к функции Spotlight также можно получить с помощью сочетания клавиш “Cmd + пробел”

- Введите “терминал” в поле поиска, и оно появится в результатах поиска.

- Дважды щелкните “Терминал” вариант для запуска командной строки.

Открыть терминал с помощью Finder
- Перейдите в Dock и нажмите “Finder” значок. Это похоже на двухцветное улыбающееся лицо.

- Выберите “Приложения” на левой панели Finder. Если его там нет, нажмите “Перейти” в верхней части экрана, затем нажмите “Приложения”

- Выберите “Утилиты”

- Дважды нажмите &ldquo ;Терминал” для перехода к командной строке.

Команды терминала
Вы можете выполнять команды в Терминале, вводя команду, затем нажмите клавишу возврата. После этого Терминал должен предоставить любую соответствующую информацию.
Ниже приведен список операционных команд, которые помогут вам начать работу в Терминале и помогут расширить ваши знания о командной строке.
Изменить каталог
“CD” Команда изменит каталог терминала, в котором вы работаете. Это позволит вам открыть файл, выполнить команду и просмотреть содержимое другого каталога.
Список каталогов
Кнопка “Is” Команду можно использовать при просмотре файлов и каталогов текущего каталога. Используйте “IS -I” чтобы найти дополнительную информацию о файле, включая дату создания, разрешения и владельца.
Открыть файлы
“открытый” Команда откроет файл. Введя эту команду, пробел, а затем имя файла, к которому вы хотите получить доступ, вы запустите файл с помощью соответствующего приложения, например “Word” например.
Копировать в другой каталог
“cp” Команда позволяет скопировать файл из одного места в другое или создать новую копию файла с новым именем. При указании первого значения укажите исходный файл, который вы хотите скопировать, а затем пробел и полный путь, имя файла и расширение, куда вы хотите поместить новую копию.
Пример: “ cp [имя файла] [новое имя файла]“.
Создать текстовый файл
“касание” Команда создает пустой файл любого типа. Создав пустой файл, вы можете запустить его в текстовом редакторе с помощью кнопки “open” команда.
Пример: “touch newfile.txt.”
Создать каталог
Если вам нужно другое место для хранения новых файлов, “mkdir” Команда создает новый каталог (папку). Новый каталог будет добавлен к каталогу, в котором вы работаете, или вы можете указать путь, куда вы хотите его направить.
Пример: “mkdir path/to/new/directory.&rdquo ;
Переместить файл

“mv” Команда предназначена для случаев, когда вы хотите переместить файл, а не делать его копию. Он переместит указанный файл из исходного местоположения в новое.
Пример: “mv [filename] path/to/new/file/location.
Копировать Содержимое папки в новую папку

Точно так же, как английское значение “ditto” эту команду можно использовать, чтобы сделать то же самое снова. Он выполнит копию всего содержимого одной папки в указанную вами папку. Это идеально, если вам нужно начать новый проект и использовать существующий в качестве основы.
Удалить каталог

“rmdir” Команда позволяет удалить каталог, созданный по ошибке. Если, например, вы неправильно назвали папку, вы можете переименовать ее с помощью “mv” или удалите его с помощью команды “rmdir” включая путь к каталогу.
Удалить вложенные каталоги
Команда “rm-R” Команда удаляет целые каталоги, содержащие другие каталоги или файлы. Эта команда необратима; после выполнения все каталоги и файлы по указанному вами пути будут немедленно удалены.
Список запущенных компьютерных процессов

“верхний” команда выведет статистику вашей системы в окно терминала. Информация будет включать использование процессора, памяти и диска. Отобразится список наиболее активно работающих приложений, использующих ЦП, включая используемые порты, их состояние, память для каждого приложения и многое другое. Эта команда будет выполняться до тех пор, пока вы не нажмете “control + c” , чтобы вернуться в интерфейс командной строки или выйти из терминала.
Выйти из подэкрана и вернуться в терминал
Кнопка “q” Команда идеально подходит для выхода из команд, которые выполняются бесконечно при выполнении, например “top” команда. Вы можете быстро завершить процесс выполнения, нажав клавишу “q” кнопку на клавиатуре или сочетание клавиш “control + c”
Как выйти из Терминала
Выйти из Терминала очень просто; вот как:
- Нажмите “Терминал” в главном меню Apple.

- Выберите “Выйти из терминала”
В вашей команде
Терминал — это приложение командной строки для macOS . Доступ к нему можно получить через Launchpad, Finder или через “терминал” поиск в Spotlight.
Интерфейс командной строки можно считать “Святым Граалем” управления macOS. Когда-то это был единственный способ сделать что-либо на компьютере. Короче говоря, многие технические специалисты предпочитают использовать командную строку для точного и быстрого выполнения запросов.
Удалось ли вам успешно открыть Терминал? Выполняли ли вы какие-либо команды, и если да, то работали ли они должным образом? Расскажите нам о своем опыте с Терминалом в разделе комментариев ниже.