Mac OS X terminal 101: terminal usage tutorial

Source: Internet
Author: User
Tags clear screen

I recently learned Apple's Mac OS x support essentials. I have learned a lot about command line. Next I will take some translations and notes, as shown below.

You can drive cars all day without knowing how to fix them, but if you want to be a maintainer, you need to know how things work. The same thing happened on Mac OS X. You can always use Mac instead of knowing how to fix it, but if you want to maintain or solve some problems for the system, then you need to know how to use command-line.

Why do I need to use the command line or how to enable the command line?
  • Many functions are not provided in the GUI and can only be implemented through command lines.

  • The Finder hides many files that you do not need, but the command line allows you to access all files.

  • You can use command line to remotely access your Mac (using SSH ).

  • You can usesudoCommand to obtain the root user permission.

  • You can use command-line script to make your work more efficient.

  • The terminal program can be found in utility.

  • If you enable manual user name login mode, enter>consoleYou can directly access the command line interface. Then you still need to log on to an account.


First knowledge of command line
  • Many Commands take some time to execute, but there is no prompt or progress bar in the middle. Generally, a "User Name $" mark will appear after the end. If not, the last command is being executed.

  • A command consists of four parts: command name, options, arguments, and extras, but the last three parts are sometimes optional. Options-As a leading character. The options section of many commands only contains a single letter, which can be merged. For example,ls -lAAndls -l -AIs equivalent. The arguments part is used to refine the command or specify the specific implementation object of the command, and the extras part is used to further implement other functions.

  • For example, the following command contains the first three parts used to delete the junk program.
    michelle$ rm -R /Applications/Junk.app

  • If you enter some wrong commands, the system will return some error messages. However, the system does not prevent you from doing stupid things (such as deleting the entire user folder ).

Man command

Although there are thousands of commands, each command has many optional parameters and specific usage methods, you do not need to remember these commands. You only need to remember one:man

Most commands will contain a user guide, which will tell you all the details about the command you need to know, enterman command-name. For example, you want to knowlsHow to use this command, enterman lsTo go to the user guide page.

The User Guide is often very long, so you can use ▲ (up arrow) or ← (down arrow) to move up and down, use to flip pages, enter/And keywords to search by keyword, and press Q to exit the user guide page.

So -- what if you don't even know the command name? Inputman -kAnd keywords to search the entire user guide database.

Command Line, file, and Path

If you know how to use commands is the first step to master command line, the second step is to learn how to use the file path in command line. If you have mastered the file path, you will find that this is faster than using the finder.

Note:

  • The command line tool is case sensitive and must include an extension for file names. For example, if you want to find the iTunes program, enteritunesIt is invalid and must be inputiTunes.app.

  • Mac OS traditionally prefers the "folder" name, but in command line, it mainly uses the word "directory. This is consistent with Unix.

Two paths: absolute path and relative path
  • Absolute path: a complete description of the location of a file, always with a slash (/) (Forward slash. For example/Users/michelle/Public/Drop Box.

  • Relative Path: only part of the location information is described. It is related to your current directory in command line. When you open a new terminal program, the Directory of the command line session should be your home folder.ThenRelative Path Writing of the folder in the above examplePublic/Drop Box. Apparently it starts from the current directory. Similar to HTML, you can also use two vertices (..") To represent the parent directory, so that you can use the relative path to represent the parent or peer directory. For example, you can entercd ..Evencd ../..

Switch to another path and Directory

To switch the current command line session to another directory, you need to use three commands:pwd,lsAndcd.

  1. pwdThe meaning is "Print working directory". The absolute path of the current directory is displayed.

  2. lsThe description is "list directory contents", which lists the contents of the current directory. This command has other optional parameters.

  3. cdThe meaning is "Change directory", which will change the current directory to the directory you specified. If you do not specify this parameter, your home folder is returned.

Handling special characters

If the directory contains special characters (space, Parentheses, quotation marks,[],!,$,&,*,;,|,\), Then entering a space directly will make the system difficult to identify. Special syntax must be used to represent these characters. For example, in the above example, add the Backslash"\(Back slash:cd Punlic/Drop\ Box/. In addition to the backslash, you can also use the quotation mark method:cd "Public/Drop Box"。

-- If you do not want to enter the file manually, you can drag the file from the Finder to the terminal window to create an absolute path, which is convenient, because all the special characters mentioned above are automatically converted into a recognizable representation after being dragged. In fact, a more efficient solution is to use the tab complete function.

Tab complete is one of the most time-saving features in command line. It can be used to automatically complete the file and directory name function and prevent input errors. UsecdGo to your home folder and usecd PCommand, and then press the tab button. You may hear an error because your home folder contains multiple folders starting with P. Press tab again, and terminal will list the two folders starting with P: public and pictures. Press U, then press tab, and terminal will automatically complete for youPublic/. Tab complete also processes those special characters. Note that this will be retained at the end/This is normal most of the time, but if an error occurs, remove unnecessary/Try it.

In addition, e-fu~(Tilde) in command line, it can represent the current user's home folder. For example~/Public/Drop\ Box/It is legal.

View hidden files

To simplify the work, both command line and finder can hide many files and folders, which are usually required by the system. It is difficult for the Finder to show hidden files without using third-party tools, but it is very simple in command line. First, many hidden files are hidden in the Finder by hiding properties, while command line ignores these properties, so these files are displayed in command line. In addition,lsCommand to hide the file name.But these files can be displayed by using-a. For example:

michelle$ ls -la

We also added-lTo control the output format. If you pay attention to the output content, you will find that.And..The current folder and the parent folder (). If you do not want to display the two items, you only need-aChange-AYou can.


Go to other volumes

In command line, the system volume (also known as root volume) is represented by a forward slash from the beginning. However, it may sound incredible that other volumes in command line appear in a folder named volumes in the file system. The following command clearly shows the logical relationship: I started from my home folder and finally went to a volume called time machine, which is external to the Mac.

bogon:~ renfei$ pwd
/Users/renfei
bogon:~ renfei$ cd /Volumes/
bogon:Volumes renfei$ pwd
/Volumes
bogon:Volumes renfei$ ls
Macintosh SSD      Time Machine
bogon:Volumes renfei$ cd Time\ Machine/
bogon:Time Machine renfei$ pwd
/Volumes/Time Machine
Use command-line to manage files View files

There are many basic commands used to locate and view files and folders, includingcat,less,which,fileAndfind. Don't forget, you can usemanCommand to view the user guide for each command.

Cat

catIt means "concatenate". The file is read in order and output to the terminal window. The syntax iscatThe path of the file to be viewed.catCommand can also be used>>To add text files, such as commandscat ../textOne.txt >> textTwo.txtThe content of textone.txt is added to the end of texttwo.txt. This>>It belongs to the "extras" mentioned in the previous article ".

Less

This command is more suitable for viewing long text files because it allows you to search for text. Syntax:lessAndcatSame. UselessThe file opened by the command is actually a viewer used when you view the command User Guide, so the operation is the same. You can also use the ▲ (up arrow) or ← (down arrow) to move text up and down./And keywords to search by keyword, and press Q to exit the user guide page. In addition, press the V Key to useviText Editor.

Which

This command locates the file path of a command. In other words, it will tell you which file you are using when executing a specific command. Syntax:whichFollowed by a command.


File

This command will try to output the file type according to the file content. If the extension of a file is missing, this command may be very useful. Syntax:filePath to the file ., This example is a PNG file, which also provides its size, number of colors, and other information.


Find

This command is used to locate the file path based on the search keyword.findThe command does not use spotlight to search for services, but it allows you to set very specific search conditions and wildcards (described later ). Syntax:findFollowed by the START path of the search, followed by defining the search options, followed by the search content (included in quotation marks ). For example:


Note:

  1. If you want to search for the root directory, you may want to use-xTo avoid searching for/volumes folders.

  2. If you want to use the soptlight search service, usemdfindCommand and then search for keywords.

Use wildcards (wildcard characters)

The following are common wildcards:

  • Asterisk (*, asterisk) -- represents any character of any length. For example*.tiffIndicates all files in the TIFF format.

  • Question mark (?, Question mark) -- represents any single character. For exampleb?okMatch book but not brook.

  • Square brackets ([], square brackets) -- define a certain range of characters, such[Dd]ocumentMatch document and document;doc[1-9]Match doc1, doc2,..., doc9.

Using the above three wildcards can greatly improve the efficiency.

Use recursive commands

To put it simply, recursive commands allow a command to run all files in a specified path instead of a specific file. Most commands contain-rOr-RTo set whether you want to recursively execute this command. For example, the following example shows how to add-RAfterlsCommand Execution method:


Edit files and folders

There are many basic commands used to edit files and folders, includingmkdir,cp,mv,rm,rmdirAndvi. The following is a brief introduction to these commands.

Mkdir

The abbreviation of "make diretory" is used to create a folder. The syntax ismkdirAnd the directory of the new folder. Available-pTo create a folder that does not exist in the path ).

CP

The abbreviation of "copy" is used to copy an object from one place to another. Syntax:cpThe original path is followed by the target path. If you want to copy the entire folder and all the content, you need to add-R. If the specified target path does not contain a file name, the CP Command copies the file according to its original name. If the specified target path contains a file name, the specified file name will be copied. If only the new file name is specified, a copy of the file is created with the new name in the original file. Note: The system will automatically replace the file with the same name without prompting.

MV

The abbreviation of "move" is used to move a file. Syntax:mvAnd then the new path. The rules for the specified path of the MV are the same as those for the CP (yes, if you only specify the new file name, it becomes the RENAME command ).

Rm

The abbreviation of "Remove" will permanently delete the file. Note that there is no paper basket in command-line. Syntax:rmPath of the file. However, files deleted using the RM command may be recovered using data recovery tools. If you want to safely delete files, you can usesrmCommand.

Rmdir and RM-R

Rmdir is the abbreviation of "Remove directory". This command permanently deletes the folder. Again, the CLI contains a waste bin. Syntax:rmdirThe path of the directory to be deleted. However, the rmdir command cannot delete folders containing any other files, so in most casesrmdirCommand is not applicable. However, you can usermAdd-RTo delete folders and all files.

VI

It represents "visual", but the name is rather ironic: VI may be the worst-performing text editor. However, VI is the most common text editor in command line. To open a text file with Vi, you only need to enterviAnd the file path. Mac OS X also providesnano, A more modern text editor. It is also more convenient. For example, there is a cheat note (= _ =) at the bottom, and there is a list of commonly used shortcut keys (you don't need to memorize them ). However, VI is sometimes the default text editor, so it is very useful to master VI.

AndlessCommand is similar,viThe command occupies the entire terminal space to display the file content. After it is enabled, in "command mode", VI will wait for you to enter some predefined characters to tell VI what you want to do. You can also use the arrow keys on the keyboard to browse files. When you want to edit a, press a to start (the edit mode is displayed ). The text is inserted at the cursor. If you want to save the settings, exit edit mode and enter command mode. Press the ESC key. Return to command mode, hold down SHIFT and press Z twice to save and exit. If you do not want to save it, enter:quit!And press ENTER
Return directly exits.

Use command-line to manage the system Use Su to switch users

suThe command represents "substitute user identity", allowing you to easily switch to another user account in the command line. Syntax:suFollowed by the short name of the user. Then you will be asked to enter the password (but it will not be displayed when you enter it ). After the command is executed, the prefix of the command changes, indicating that you have the rights of other users. You can usewho -mCommand to verify the identity of the current login. After switching, you will keep the user's identity until you exit terminal or enterexitCommand.

Use of sudo Sudo Overview

The more powerful command issudo, Which indicates "substitute user do", or, more appropriately, "Super User do ". UsesudoThe root account permission is used to execute a command. Of course, you need to grant permissions to the administrator account (such as the password ).

By default, any administrator account can usesudoTo obtain the root permission, even if the root account is disabled on the GUI,sudoStill valid. This command is the reason we have to use terminal in many cases, which is also a danger to the identity of every user administrator. However, you can adjustsudoTo restrict its use.

bogon:~ renfei$ cat secret.txt
cat: secret.txt: Permission denied
bogon:~ renfei$ sudo cat secret.txtPassword:This is the contents of the secret.txt text file that the user account renfei does not normally have access permissions to read. However, because he is an administrative user, she can use the sudo command to envoke root user access and read the contents of this file.

Prompt: If you forget to usesudoThe command line returns an error. You only need to entersudo !!You can usesudoTo execute the previous command.

Remember, the larger the power, the greater the responsibility. Improper UsesudoIt can easily damage your system settings. The command line will only prompt you before you execute the first severe destructive behavior, and then it will assume that you know what you are doing. If you only have three guidelines for using command line, it will be: Always check your command carefully; always use tab completion to help you avoid spelling mistakes; UsesudoPreviously, I always carefully checked your commands.

Switch Shell Using sudo

If you are an administrator, You need to execute many commands that require root permissions. You can temporarily switch the entire command line shell to obtain root-level access permissions. The method is to entersudo -sAnd press enter to enter your password.

Other command-line tips
  • Enter the commandopen .You can use the Finder to open the current location.

  • In the terminal preference, you can set its appearance and style.

  • To abort a wrong or crazy command, you can use the combination key control + C.

  • You can edit the command before executing it. You only need to use the arrow and other letters on the keyboard.

  • If you have not entered any commands, you can use ▲ and history to view historical commands. You can also edit and execute again.

  • You can also usehistoryCommand to view the history.

  • You can use the combination key control + l clear screen.


Mac OS X terminal 101: terminal usage tutorial

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.