[关闭]
@Sarah 2016-01-08T01:37:04.000000Z 字数 31731 阅读 2097

command line by codeacademy

未分类


The command line is a text interface for your computer. It's a program that takes in commands, which it passes on to the computer's operating system to run.

From the command line, you can navigate through files and folders on your computer, just as you would with Finder on Mac OS or Windows Explorer on Windows. The difference is that the command line is fully text-based.

The advantage of using the command line is its power. You can run programs, write scripts to automate common tasks, and combine simple commands to handle difficult tasks - making it an important programming tool.

This course is for unix-based systems such as Linux and Mac OS X. An appendix of all commands taught in this course is available here.
1.
To access the command line, we use a terminal emulator, often just called the terminal.

In the terminal, after the $ type:

ls

列出来当前文件夹里的内容

and press Enter.

You should see three items print out below the command.

Click Next to learn how this command works.

What's going on here?

$ ls
2014 2015 hardware.txt

In the terminal, first you see $. This is called a shell prompt. It appears when the terminal is ready to accept a command.
When you type ls, the command line looks at the folder you are in, and then "lists" the files and folders inside it. The directories 2014, 2015, and the file hardware.txt are the contents of the current directory.
ls is an example of a command, a directive to the computer to perform a specific task.
When using the command line, we refer to folders as directories. Files and directories on your computer are organized into a filesystem.

Click Next to find out how the filesystem works.
此处输入图片的描述

A filesystem organizes a computer's files and directories into a tree structure:

The first directory in the filesystem is the root directory. It is the parent of all other directories and files in the filesystem.
Each parent directory can contain more child directories and files. Here blog/ is the parent of 2014/, 2015/, and hardware.txt.
Each directory can contain more files and child directories. The parent-child relationship continues as long as directories and files are nested.
You're probably already familiar with this tree structure - Mac Finder and Windows Explorer represent the filesystem as trees as well.

At any point, you can reference the filesystem for this lesson here.
Instructions
1.
Let's see how to navigate the filesystem from the command line. In the terminal, after the shell prompt, type

pwd

and press Enter. We'll explain this in the next exercise.
$ pwd
/home/ccuser/workspace/blog

pwd stands for "print working directory". It outputs the name of the directory you are currently in, called the working directory.

Here the working directory is blog/. In Codecademy courses, your working directory is usually inside the home/ccuser/workspace/ directory.

Together with ls, the pwd command is useful to show where you are in the filesystem.
1.
Let's continue with more commands. In the terminal, print the working directory.
2.
List all files and directories in the working directory.
3.
Then type

cd 2015

Again, print the new current working directory.

List all files and directories in the working directory.

Workspace ready

  1. $ pwd
  2. /home/ccuser/workspace/blog
  3. $ ls
  4. 2014 2015 hardware.txt
  5. $ cd 2015
  6. $

$ cd 2015

cd stands for "change directory". Just as you would click on a folder in Windows Explorer or Finder, cd switches you into the directory you specify. In other words, cd changes the working directory.
The directory we change into is 2015. When a file, directory or program is passed into a command, it is called an argument. Here the 2015 directory is an argument for the cd command.
The cd command takes a directory name as an argument, and switches into that directory.
1.
Change into the 2015/ directory again.
2.
Then type

cd jan/memory/

Print the working directory to see the new location.
3.
Then type

cd ..

Print the working directory again to see the new location.

                        $ cd jan/memory

To navigate directly to a directory, use cd with the directory's path as an argument. Here, cd jan/memory/ command navigates directly to the jan/memory directory.

$ cd .. 回到上一级目录

To move up one directory, use cd ... Here, cd .. navigates up from jan/memory/ to jan/.
1.
Change the directory to the 2015/feb/ directory.

List all files and directories in the working directory.
2.
Type

mkdir media

Again, list all files and directories in the working directory. You'll see that there is now a new directory named media/.

$ mkdir media 制造新目录名字是media

The mkdir command stands for "make directory". It takes in a directory name as an argument, and then creates a new directory in the current working directory.

Here we used mkdir to create a new directory named media/ inside the feb/ directory.
1.
Navigate to the 2014/dec/ directory.

List all files and directories in the working directory.
2.
Then type

touch keyboard.txt 新建文件

Again, list all files and directories in the working directory. You'll see that there is now a new file named keyboard.txt.
touch keyboard.txt

The touch command creates a new file inside the working directory. It takes in a filename as an argument, and then creates an empty file in the current working directory.

Here we used touch to create a new file named keyboard.txt inside the 2014/dec/ directory.
Instructions
The commands we've covered so far are commonly used to navigate the filesystem. There are more commands you can use to master the command line, and we'll cover them in the next lessons.

Let's summarize what we've done so far.

Congratulations! You've learned five commands commonly used to navigate the filesystem from the command line. What can we generalize so far?

The command line is a text interface for the computer's operating system. To access the command line, we use the terminal.
A filesystem organizes a computer's files and directories into a tree structure. It starts with the root directory. Each parent directory can contain more child directories and files.
From the command line, you can navigate through files and folders on your computer:

pwd outputs the name of the current working directory.

ls lists all files and directories in the working directory.

cd switches you into the directory you specify.
mkdir creates a new directory in the working directory.

touch creates a new file inside the working directory.

$ ls -a
. .. .preferences action drama comedy genres.xt

The ls command lists all files and directories in the working directory.
The -a modifies the behavior of the ls command to also list the files and directories starting with a dot (.). Files started with a dot are hidden, and don't appear when using ls alone.
The

-a 和ls一起用

is called an option. Options modify the behavior of commands. Here we used ls -a to display the contents of the working directory in more detail.

In addition to -a, the ls command has several more options. Here are three common options:

-a - lists all contents, including hidden files and directories

-l - lists all contents of a directory in long format

-t - order files and directories by the time they were last modified.

Let's practice using these options below.
Instructions
1.
In the terminal, type

ls -l

Click Next to find out what these columns mean.

$ ls -l

drwxr-xr-x 5 cc eng 4096 Jun 24 16:51 action
drwxr-xr-x 4 cc eng 4096 Jun 24 16:51 comedy
drwxr-xr-x 6 cc eng 4096 Jun 24 16:51 drama
-rw-r--r-- 1 cc eng 0 Jun 24 16:51 genres.txt

The -l option lists files and directories as a table. Here there are four rows, with seven columns separated by spaces. Here's what each column means:

Access rights. These are actions that are permitted on a file or directory.
Number of hard links. This number counts the number of child directories and files. This number includes the parent directory link (..) and current directory link (.).
The username of the file's owner. Here the username is cc.
The name of the group that owns the file. Here the group name is eng.
The size of the file in bytes.
The date & time that the file was last modified.
The name of the file or directory.
1.
Let's try out another option for the ls command.

Navigate to the comedy/ directory.
2.
Then type

ls -alt

$ ls -alt

drwxr-xr-x 4 cc eng 4096 Jun 29 12:22 .
-rw-r--r-- 1 cc eng 0 Jun 29 12:22 .gitignore
drwxr-xr-x 5 cc eng 4096 Jun 30 14:20 ..
drwxr-xr-x 2 cc eng 4096 Jun 29 12:22 satire
drwxr-xr-x 2 cc eng 4096 Jun 29 12:22 slapstick
-rw-r--r-- 1 cc eng 14 Jun 29 12:22 the-office.txt

The -t option orders files and directories by the time they were last modified.

In addition to using each option separately, like ls -a or ls -l, multiple options can be used together, like ls -alt.

Here, ls -alt lists all contents, including hidden files and directories, in long format, ordered by the date and time they were last modified.
1.
Let's move on to copying, moving, and removing files and directories from the command line.

Navigate to the drama/biopic/ directory.

List all files and directories in the working directory.
2.
Then type

cp frida.txt lincoln.txt

Click Next to learn about this command.

cp frida.txt lincoln.txt

The cp command copies files or directories. Here, we copy the contents of frida.txt into lincoln.txt.

1.
There are a few more ways to use cp.

Navigate to the drama/ directory.

List all files and directories in the working directory.
2.
Type

cp biopic/cleopatra.txt historical/

3.
Navigate to the historical/ directory.

List all files and directories in the working directory. You should see a new copy of cleopatra.txt in this directory.
4.
Here's one more way to use cp.

Navigate up one directory from drama/historical/ to drama/. (Here's a hint on how to do this.)
5.
Then type

cp biopic/ray.txt biopic/notorious.txt historical/

6.
Change directories into historical/.

List all files and directories in the working directory. You should see a new copy of ray.txt and notorious.txt in this directory.

  1. $ cd drama/directory
  2. bash: cd: drama/directory: No such file or directory
  3. $ cd drama/
  4. $ cp biopic/cleopatra.txt historical/
  5. $ cd historical/
  6. $ ls
  7. cleopatra.txt gladiator.txt selma.txt
  8. $ cd ..
  9. $ cp bio[ic/ray.txt
  10. cp: missing destination file operand after bio[ic/ray.txt
  11. Try 'cp --help' for more information.
  12. $ cp biopic/ray.txt biopic/notorious.txt historical/
  13. $ cd historical/
  14. $ ls
  15. cleopatra.txt gladiator.txt notorious.txt ray.txt selma.txt
  16. $

cp biopic/cleopatra.txt historical/

To copy a file into a directory, use cp with the source file as the first argument and the destination directory as the second argument. Here, we copy the file biopic/cleopatra.txt and place it in the historical/ directory.

cp biopic/ray.txt biopic/notorious.txt historical/

To copy multiple files into a directory, use cp with a list of source files as the first arguments, and the destination directory as the last argument. Here, we copy the files biopic/ray.txt and biopic/notorious.txt into the historical/ directory.

  1. Workspace ready
  2. $ cd comedy/
  3. $ torch shrek.txt
  4. bash: torch: command not found
  5. $ touch shrek.txt
  6. $ cp*satire/
  7. bash: cp*satire/: No such file or directory
  8. $ sp * satire/
  9. bash: sp: command not found
  10. $ cp * satire/
  11. cp: omitting directory satire
  12. cp: omitting directory slapstick
  13. $ cd satire/
  14. $ ls
  15. fight-club.txt shrek.txt the-office.txt
  16. $ cd action/
  17. bash: cd: action/: No such file or directory
  18. $ cd ../../action/
  19. $ cp m 8.txt scifi/
  20. cp: cannot stat m’: No such file or directory
  21. cp: cannot stat 8.txt’: No such file or directory
  22. $ cp m*.txt scifi/
  23. $ cd scifi/
  24. $ ls
  25. matrix-reloaded.txt matrix-revolutions.txt matrix.txt terminator.txt
  26. $

cp * satire/

In addition to using filenames as arguments, we can use special characters like * to select groups of files. These special characters are called wildcards. The * selects all files in the working directory, so here we use cp to copy all files into the satire/ directory.

cp m*.txt scifi/

Here, m*.txt selects all files in the working directory starting with "m" and ending with ".txt", and copies them to scifi/.

  1. Workspace ready
  2. $ cd action/
  3. $ mv superman.txt superhero/
  4. $ cd superhero/
  5. $ ls
  6. batman.txt superman.txt
  7. $ cd ..
  8. $ mv wonderwoman.txt batman.txt superhero/
  9. $ cd superhero/
  10. $ ls
  11. batman.txt superman.txt wonderwoman.txt
  12. $ mv batman.txt spiderman.txt
  13. $ ls
  14. spiderman.txt superman.txt wonderwoman.txt
  15. $ ```
  16. The mv command moves files. It's similar to cp in its usage.
  17. #mv superman.txt superhero/
  18. To move a file into a directory, use mv with the source file as the first argument and the destination directory as the second argument. Here we move superman.txt into superhero/.
  19. #mv wonderwoman.txt batman.txt superhero/
  20. To move multiple files into a directory, use mv with a list of source files as the first arguments, and the destination directory as the last argument. Here, we move wonderwoman.txt and batman.txt into superhero/.
  21. #mv batman.txt spiderman.txt
  22. To rename a file, use mv with the old file as the first argument and the new file as the second argument. By moving batman.txt into spiderman.txt, we rename the file as spiderman.txt.
  23. ```
  24. $ cd comedy/slapstic
  25. bash: cd: comedy/slapstic: No such file or directory
  26. $ cd comedy/slapstick
  27. $ ls
  28. waterboy.txt zoolander.txt
  29. $ rm waterboy.txt
  30. $ ls
  31. zoolander.txt
  32. $ cd ..
  33. $ rm -r slapstick
  34. $ ls
  35. satire shrek.txt the-office.txt
  36. $

rm waterboy.txt

The rm command deletes files and directories. Here we remove the file waterboy.txt from the filesystem.

rm -r comedy

The -r is an option that modifies the behavior of the rm command. The -r stands for "recursive," and it's used to delete a directory and all of its child directories.

Be careful when you use rm! It deletes files and directories permanently. There isn't an undelete command, so once you delete a file or directory with rm, it's gone.

           Congratulations! You learned how to use the command line to view and manipulate the filesystem. What can we generalize so far?

Options modify the behavior of commands:

ls -a lists all contents of a directory, including hidden files and directories
ls -l lists all contents in long format
ls -t orders files and directories by the time they were last modified
Multiple options can be used together, like ls -alt
From the command line, you can also copy, move, and remove files and directories:
cp copies files
mv moves and renames files
rm removes files
rm -r removes directories
Wildcards are useful for selecting groups of files and directories


Up until now, we have run commands in the command line and received a stream of output in the terminal. In this lesson, we'll focus on input and output (I/O) redirection.

Through redirection you can direct the input and output of a command to and from other files and programs, and chain commands together in a pipeline. Let's try it out.

You can reference the filesystem for this lesson here.
1.
Let's begin by taking a closer look at input and output.

In the terminal, after the shell prompt, type

echo "Hello"类似打印

  1. $ echo "Hello"
  2. Hello
  3. $

The echo command accepts the string "Hello" as standard input, and echoes the string "Hello" back to the terminal as standard output.

Let's learn more about standard input, standard output, and standard error:

1.standard input 输入

, abbreviated as stdin, is information inputted into the terminal through the keyboard or input device.

2.standard output 输出

, abbreviated as stdout, is the information outputted after a process is run.

3.standard error错误

, abbreviated as stderr, is an error message outputted by a failed process.

Redirection reroutes standard input, standard output, and standard error to or from a different location.

  1. $ echo "Hello" > hello.txt
  2. $ cat hello.txt
  3. Hello

How does redirection work?

$ echo "Hello" > hello.txt 写进文件

The > command redirects the standard output to a file. Here, "Hello" is entered as the standard input. The standard output "Hello" is redirected by > to the file hello.txt.

$ cat hello.txt 打印文件里内容

The cat command outputs the contents of a file to the terminal. When you type cat hello.txt, the contents of hello.txt are displayed.

  1. $ ls -l
  2. total 44
  3. -rw-r--r-- 1 ccuser ccuser 69 Jul 17 15:20 continents.txt
  4. -rw-r--r-- 1 ccuser ccuser 135 Jul 17 15:11 deserts.txt
  5. -rw-r--r-- 1 ccuser ccuser 223 Jul 17 16:29 forests.txt
  6. -rw-r--r-- 1 ccuser ccuser 179 Jul 17 15:11 glaciers.txt
  7. -rw-r--r-- 1 ccuser ccuser 6 Jan 6 22:50 hello.txt
  8. -rw-r--r-- 1 ccuser ccuser 191 Jul 17 15:12 islands.txt
  9. -rw-r--r-- 1 ccuser ccuser 140 Jul 17 16:00 lakes.txt
  10. -rw-r--r-- 1 ccuser ccuser 248 Jul 17 16:04 mountains.txt
  11. -rw-r--r-- 1 ccuser ccuser 71 Jul 17 15:12 oceans.txt
  12. -rw-r--r-- 1 ccuser ccuser 164 Jul 17 15:59 rivers.txt
  13. -rw-r--r-- 1 ccuser ccuser 204 Jul 17 15:13 volcanoes.txt
  14. $ cat oceans.txt > continents.txt
  15. $ act continents.txt
  16. bash: act: command not found
  17. $ cat continents.txt
  18. Arctic Ocean
  19. Atlantic Ocean
  20. Indian Ocean
  21. Pacific Ocean
  22. Southern Ocean
                                                    #cat oceans.txt > continents.txt  覆盖

’ > takes the standard output of the command on the left, and redirects it to the file on the right. Here the standard output of cat oceans.txt is redirected to continents.txt.

Note that > overwrites all original content in continents.txt. When you view the output data by typing cat on continents.txt, you will see only the contents of oceans.txt. #$ cat oceans.txt > continents.txt

‘ > takes the standard output of the command on the left, and redirects it to the file on the right. Here the standard output of cat oceans.txt is redirected to continents.txt.

Note that > overwrites all original content in continents.txt. When you view the output data by typing cat on continents.txt, you will see only the contents of oceans.txt.
$ cat oceans.txt > continents.txtf

’ > takes the standard output of the command on the left, and redirects it to the file on the right. Here the standard output of cat oceans.txt is redirected to continents.txt.

Note that > overwrites all original content in continents.txt. When you view the output data by typing cat on continents.txt, you will see only the contents of oceans.txt.

  1. $ cat glaciers.txt >> rivers.txt
  2. $ cat rivers.txt
  3. Nile River
  4. Amazon River
  5. Yangtze River
  6. Mississippi River
  7. Paraná River
  8. Congo River
  9. Mekong River
  10. Mackenzie River
  11. Niger River
  12. Euphrates River
  13. Yukon River
  14. Indus River
  15. Perito Moreno Glacier
  16. Margerie Glacier
  17. Furtwängler Glacier
  18. Pasterze Glacier
  19. Vatnajökull Glacier
  20. Fox Glacier
  21. Biafo Glacier
  22. Canada Glacier
  23. Yulong Glacier
  24. Jostedalsbreen Glacier

$ cat glaciers.txt >> rivers.txt 附加

‘ >> takes the standard output of the command on the left and appends (adds) it to the file on the right. You can view the output data of the file with cat and the filename.

Here, the the output data of rivers.txt will contain the original contents of rivers.txt with the content of glaciers.txt appended to it.

$ cat < lakes.txt
Caspian Sea
Lake Superior
Lake Victoria
Lake Michigan
Lake Taganyika
Lake Baikal
Great Bear Lake
Lake Malawi
Lake Titicaca
Lake Nicaragua

$ cat < lakes.txt 右边的输出到左边

< takes the standard input from the file on the right and inputs it into the program on the left. Here, lakes.txt is the standard input for the cat command. The standard output appears in the terminal.

```
$ cat volcanoes.txt | wc                                                                         
         17      26     204                                                                          
    $ cat volcanoes.txt |wc | cat > islands.txt                                                      
$ cat volcanoes.txt | wc | cat > islands.txt                                                     
    $ cat islands.txt                                                                                
     17      26     204                                                                          
$                                                         ``` 

$ cat volcanoes.txt | wc 左边的输入变成右边的输出

| is a "pipe". The | takes the standard output of the command on the left, and pipes it as standard input to the command on the right. You can think of this as "command to command" redirection.

Here the output of cat volcanoes.txt is the standard input of wc. in turn, the wc command outputs the number of lines, words, and characters in volcanoes.txt, respectively.

$ cat volcanoes.txt | wc | cat > islands.txt

Multiple |s can be chained together. Here the standard output of cat volcanoes.txt is "piped" to the wc command. The standard output of wc is then "piped" to cat. Finally, the standard output of cat is redirected to islands.txt.

You can view the output data of this chain by typing cat islands.txt.


  1. Lake Superior
  2. Lake Victoria
  3. Lake Michigan
  4. Lake Taganyika
  5. Lake Baikal
  6. Great Bear Lake
  7. Lake Malawi
  8. Lake Titicaca
  9. Lake Nicaragua
  10. $ sort lakes.txt
  11. Caspian Sea
  12. Great Bear Lake
  13. Lake Baikal
  14. Lake Malawi
  15. Lake Michigan
  16. Lake Nicaragua
  17. Lake Superior
  18. Lake Taganyika
  19. Lake Titicaca
  20. Lake Victoria
  21. $ cat lakes.txt | sort > sorted-lakes.txt
  22. $ cat sorted-lakes.txt
  23. Caspian Sea
  24. Great Bear Lake
  25. Lake Baikal
  26. Lake Malawi
  27. Lake Michigan
  28. Lake Nicaragua
  29. Lake Superior
  30. Lake Taganyika
  31. Lake Titicaca
  32. Lake Victoria

$ sort lakes.txt 排序

sort takes the standard input and orders it alphabetically for the standard output. Here, the lakes in sort lakes.txt are listed in alphabetical order.

cat lakes.txt | sort > sorted-lakes.txt 左边排序写入右边

Here, the command takes the standard output from cat lakes.txt and "pipes" it to sort. The standard output of sort is redirected to sorted-lakes.txt.

You can view the output data by typing cat on the file sorted-lakes.txt.


  1. Great Basic Desert
  2. Syrian Desert
  3. Kalahari Desert
  4. $ uniq deserts.txt
  5. Arctic Desert
  6. Sahara Desert
  7. Arabian Desert
  8. Gobi Desert
  9. Kalahari Desert
  10. Great Basic Desert
  11. Syrian Desert
  12. Kalahari Desert
  13. $ sort deserts.txt | uniq
  14. Arabian Desert
  15. Arctic Desert
  16. Gobi Desert
  17. Great Basic Desert
  18. Kalahari Desert
  19. Sahara Desert
  20. Syrian Desert
  21. $ sort deserts.txt | uniq-deserts.txt
  22. bash: uniq-deserts.txt: command not found
  23. $ sort deserts.txt | uniq > uniq-deserts.txt
  24. $ cat uniq-deserts.txt
  25. Arabian Desert
  26. Arctic Desert
  27. Gobi Desert
  28. Great Basic Desert
  29. Kalahari Desert
  30. Sahara Desert
  31. Syrian Desert ```
  32. #$ uniq deserts.txt 不重复元素
  33. uniq stands for "unique" and filters out adjacent, duplicate lines in a file. Here uniq deserts.txt filters out duplicates of "Sahara Desert", because the duplicate of 'Sahara Desert' directly follows the previous instance. The "Kalahari Desert" duplicates are not adjacent, and thus remain.
  34. #排序+不重复 $ sort deserts.txt | uniq
  35. A more effective way to call uniq is to call sort to alphabetize a file, and "pipe" the standard output to uniq. Here by piping sort deserts.txt to uniq, all duplicate lines are alphabetized (and thereby made adjacent) and filtered out.
  36. #sort deserts.txt | uniq > uniq-deserts.txt 排序不重写入
  37. Here we simply send filtered contents to uniq-deserts.txt, which you can view with the cat command.
  38. ----------

$ cat mountains.txt
The Himalayas
Hindu Kush Mountains
Henduan Mountains
Tian Shan
Nyenchen Tanglha
Andes mountains
Atlas Mountains
Mount Kilimanjaro
Scandinavian mountains
Appalachian mountains
Rocky mountains
Sierra Nevada de Santa Marta
Transantarctic Mountains

grep -i Mount mountains.txt
Hindu Kush Mountains
Henduan Mountains
Andes mountains
Atlas Mountains
Mount Kilimanjaro
Scandinavian mountains
Appalachian mountains
Rocky mountains
Transantarctic Mountains

  1. #$ grep Mount mountains.txt 搜索文件里带关键词的内容
  2. grep stands for "global regular expression print". It searches files for lines that match a pattern and returns the results. It is also case sensitive. Here, grep searches for "Mount" in mountains.txt.
  3. #$ grep -i Mount mountains.txt 搜索关键词+对大小写敏感
  4. grep -i enables the command to be case insensitive. Here, grep searches for capital or lowercase strings that match Mount in mountains.txt.
  5. The above commands are a great way to get started with grep. If you are familiar with regular expressions, you can use regular expressions to search for patterns in files.
  6. $
  7. grep -R Arctic /home/ccuser/workspace/geography
  8. /home/ccuser/workspace/geography/deserts.txt:Arctic Desert
  9. /home/ccuser/workspace/geography/oceans.txt:Arctic Ocean
  10. /home/ccuser/workspace/geography/uniq-deserts.txt:Arctic Desert
  11. $ grep -Rl Arctic /home/ccuser/workspace/geography
  12. /home/ccuser/workspace/geography/deserts.txt
  13. /home/ccuser/workspace/geography/oceans.txt
  14. /home/ccuser/workspace/geography/uniq-deserts.txt
  15. $
  16. #$ grep -R Arctic /home/ccuser/workspace/geography 搜搜路径里的文件里的文字
  17. grep -R searches all files in a directory and outputs filenames and lines containing matched results. -R stands for "recursive". Here grep -R searches the /home/ccuser/workspace/geography directory for the string "Arctic" and outputs filenames and lines with matched results.
  18. #$ grep -Rl Arctic /home/ccuser/workspace/geography 搜索路径里的文件名
  19. grep -Rl searches all files in a directory and outputs only filenames with matched results. -R stands for "recursive" and l stands for "files with matches". Here grep -Rl searches the /home/ccuser/workspace/geography directory for the string "Arctic" and outputs filenames with matched results.
  20. ----------
  21. $ cat forests.txt
  22. The Amazon snowforest
  23. The Congo snowforest
  24. Valdivian Temperate snowforest
  25. Daintree snowforest
  26. Southeast Asian snowforest snowforest
  27. Tongrass National forest
  28. Sinharaja Forest Reserve
  29. Pacific Temperate snowforest snowforest
  30. $ sed 's/snow/rain/' forests.txt
  31. The Amazon rainforest
  32. The Congo rainforest
  33. Valdivian Temperate rainforest
  34. Daintree rainforest
  35. Southeast Asian rainforest snowforest
  36. Tongrass National forest
  37. Sinharaja Forest Reserve
  38. Pacific Temperate rainforest snowforest
  39. $ sed 's/snow/rain/g' forests.txt
  40. The Amazon rainforest
  41. The Congo rainforest
  42. Valdivian Temperate rainforest
  43. Daintree rainforest
  44. Southeast Asian rainforest rainforest
  45. Tongrass National forest
  46. Sinharaja Forest Reserve
  47. Pacific Temperate rainforest rainforest
  48. #$ sed 's/snow/rain/' forests.txt 搜索snow替换成rain(只替换第一个)
  49. sed stands for "stream editor". It accepts standard input and modifies it based on an expression, before displaying it as output data. It is similar to "find and replace".
  50. Let's look at the expression 's/snow/rain/':
  51. s: stands for "substitution". it is always used when using sed for substitution.
  52. snow: the search string, the text to find.
  53. rain: the replacement string, the text to add in place.
  54. In this case, sed searches forests.txt for the word "snow" and replaces it with "rain." Importantly, the above command will only replace the first instance of "snow" on a line.
  55. #$ sed 's/snow/rain/g' forests.txt全文的都替换
  56. The above command uses the g expression, meaning "global". Here sed searches forests.txt for the word "snow" and replaces it with "rain", globally. All instances of "snow" on a line will be turned to "rain".
  57. >>Congratulations! You learned how to use the command line to redirect standard input and standard output. What can we generalize so far?
  58. Redirection reroutes standard input, standard output, and standard error.
  59. The common redirection commands are:
  60. '> redirects standard output of a command to a file, overwriting previous content.
  61. >> redirects standard output of a command to a file, appending new content to old content.
  62. '< redirects standard input to a command.
  63. | redirects standard output of a command to another command.
  64. A number of other commands are powerful when combined with redirection commands:
  65. **sort:** sorts lines of text alphabetically.
  66. **uniq:** filters duplicate, adjacent lines of text.
  67. **grep:** searches for a text pattern and outputs it.
  68. **sed** : searches for a text pattern, modifies it, and outputs it.
  69. ----------
  70. Each time we launch the terminal application, it creates a new session. The session immediately loads settings and preferences that make up the command line environment.
  71. We can configure the environment to support the commands and programs we create. This enables us to customize greetings and command aliases, and create variables to share across commands and programs.
  72. 1.
  73. We'll begin by learning to use a simple, command line text editor called nano.
  74. In the terminal, type
  75. nano hello.txt
  76. This will open the nano text editor.
  77. 2.
  78. In nano, at the top of the window, type
  79. "Hello, I am nano."
  80. Using the menu at the bottom of the terminal for reference, type Ctrl + O (the letter, not the number) to save the file. This is the letter "O", not the number zero.
  81. Press Enter, when prompted about the filename to write.
  82. Then type Ctrl + X to exit nano.
  83. Finally, type clear to clear the terminal window. The command prompt should now be at the top of the window.
  84. http://www.nano-editor.org/
  85. Nice. You just edited a file in the nano text editor. How does it work?
  86. #$ nano hello.txt
  87. nano is a command line text editor. It works just like a desktop text editor like TextEdit or Notepad, except that it is accessible from the command line and only accepts keyboard input.
  88. The command nano hello.txt opens a new text file named hello.txt in the nano text editor.
  89. #"Hello, I am nano"
  90. is a text string entered in nano through the cursor.
  91. The menu of keyboard commands at the bottom of the window allow us to save changes to hello.txt and exit nano.
  92. # ^
  93. stands for the Ctrl key.
  94. #Ctrl + O
  95. saves a file. 'O' stands for output.
  96. #Ctrl + X
  97. exits the nano program. 'X' stands for exit.
  98. #Ctrl + G
  99. opens a help menu.
  100. #**clear**
  101. clears the terminal window, moving the command prompt to the top of the screen.
  102. ----------
  103. 1.
  104. Now that you are familiar with editing text in nano, let's create a file to store environment settings.
  105. In the terminal, type
  106. nano ~/.bash_profile
  107. This opens up a new file in nano.
  108. (Tip: If you are unable to type ~, you can find help here.)
  109. 2.
  110. In ~/.bash_profile, at the top of the file, type
  111. echo "Welcome, Jane Doe"
  112. You can use your name in place of "Jane Doe".
  113. Type Ctrl + O to save the file.
  114. Press Enter to write the filename.
  115. Type Ctrl + X to exit.
  116. Finally, type clear to clear the terminal window.
  117. 3.
  118. In the terminal, type
  119. source ~/.bash_profile
  120. You should see the greeting you entered.

1.
Now that you are familiar with editing text in nano, let's create a file to store environment settings.

In the terminal, type

nano ~/.bash_profile

This opens up a new file in nano.

(Tip: If you are unable to type ~, you can find help here.)
2.
In ~/.bash_profile, at the top of the file, type

echo "Welcome, Jane Doe"

You can use your name in place of "Jane Doe".

Type Ctrl + O to save the file.

Press Enter to write the filename.

Type Ctrl + X to exit.

Finally, type clear to clear the terminal window.
3.
In the terminal, type

source ~/.bash_profile

You should see the greeting you entered.

souce ~/.bash_peofile                                                                                   
bash: souce: command not found                                                                            
$ souce ~/.bash_profile                                                                                   
    bash: souce: command not found                                                                            
    $ souce ~/.bash_profile                                                                                   
bash: souce: command not found                                                                            
$ source ~/.bash_profile                                                                                  
Welcome, Jane Doe  

You created a file in nano called ~/.bash_profile and added a greeting. How does this work?

$ nano ~/.bash_profile

~/.bash_profile is the name of file used to store environment settings. It is commonly called the "bash profile". When a session starts, it will load the contents of the bash profile before executing commands.

The ~ represents the user's home directory.
The . indicates a hidden file.
The name ~/.bash_profile is important, since this is how the command line recognizes the bash profile.
The command nano ~/.bash_profile opens up ~/.bash_profile in nano.
The text echo "Welcome, Jane Doe" creates a greeting in the bash profile, which is saved. It tells the command line to echo the string "Welcome, Jane Doe" when a terminal session begins.
The command source ~/.bash_profile activates the changes in ~/.bash_profile for the current session. Instead of closing the terminal and needing to start a new session, source makes the changes available right away in the session we are in.


Now that we know what bash profile is, let's continue configuring the environment by adding command aliases.

Open ~/.bash_profile in nano.
2.
In ~/.bash_profile, beneath the greeting you created, type

alias pd="pwd"

Save the file.

Press Enter to write the filename

Exit nano.

Clear the terminal window.
3.
In the command line, use the source command to activate the changes in the current session.

source ~/.bash_profile

4.
Let's try out the alias. Type

pd

You should see the same output as you would by typing the pwd command.
`


What happens when you store this alias in ~/.bash_profile?

alias pd="pwd"

The alias command allows you to create keyboard shortcuts, or aliases, for commonly used commands.

Here alias pd="pwd" creates the alias pd for the pwd command, which is then saved in the bash profile. Each time you enter pd, the output will be the same as the pwd command.
The command source ~/.bash_profile makes the alias pd available in the current session.
Each time we open up the terminal, we can use the pd alias.


$ source                                                                                        
    bash: source: filename argument required                                                        
    source: usage: source filename [arguments]                                                      
    $ source ~/.bash_profile                                                                        
Welcome, Jane Doe                                                                               
$ hy                                                                                            
        1  nano ~/.bash_profile                                                                     
        2  clear                                                                                    
        3  source                                                                                   
        4  source ~/.bash_profile                                                                   
        5  hy                                                                                       
    $ ll                                                                                            
total 20                                                                                        
drwxr-xr-x 3 ccuser ccuser 4096 Jan  7 19:38 .                                                  
drwxr-xr-x 3 ccuser ccuser 4096 Jan  7 19:34 ..                                                 
-rw-r--r-- 1 ccuser ccuser  175 Jan  7 20:03 .test.bats                                         
drwxr-xr-x 2 ccuser ccuser 4096 Aug  1 15:03 artists                                            
-rw-r--r-- 1 ccuser ccuser   22 Jan  7 19:38 hello.txt                                          
$                                                                    

What happens when you store the following aliases in ~/.bash_profile?

alias hy="history"

hy is set as alias for the history command in the bash profile. The alias is then made available in the current session through source. By typing hy, the command line outputs a history of commands that were entered in the current session.

alias ll="ls -la"

ll is set as an alias for ls -la and made available in the current session through source. By typing ll, the command line now outputs all contents and directories in long format, including all hidden files.


1.
Now that you are familiar with configuring greetings and aliases, let's move on to setting environment variables.

Open ~/.bash_profile in nano.
2.
In the bash profile, beneath the aliases, on a new line, type

export USER="Jane Doe"

Feel free to use your own name.

Save the file.

Press Enter to write the filename.

Exit nano.

Finally, clear the terminal.
3.
In the command line, use source to activate the changes in the bash profile for the current session.
4.
Type

echo $USER

This should return the value of the variable that you set.

(Tip: If you are unable to type $, you can find help here.)


What happens when you store this in ~/.bash_profile?

export USER="Jane Doe"

environment variables are variables that can be used across commands and programs and hold information about the environment.

The line USER="Jane Doe" sets the environment variable USER to a name "Jane Doe". Usually the USER variable is set to the name of the computer's owner.
The line export makes the variable to be available to all child sessions initiated from the session you are in. This is a way to make the variable persist across programs.
At the command line, the command echo is always used when returning a variable's value. Here, the command echo $USER returns the name set for the variable.


1.
Let's learn a few more environment variables, starting with the variable for the command prompt.

Open ~/.bash_profile in nano.
2.
On a new line, beneath the last entry, type

export PS1=">> "

Save the file.

Press Enter to write the filename.

Exit nano

Finally, clear the terminal window.
3.
In the command line, use source to activate the changes in the bash profile for the current shell session.
4.
Let's try out the new command prompt. In the terminal type

echo "hello"

5.
Now type

ls -alt

Did you notice that the prompt has changed?


What happens when this is stored in ~/.bash_profile?

export PS1=">> "

PS1 is a variable that defines the makeup and style of the command prompt.

export PS1=">> " sets the command prompt variable and exports the variable. Here we change the default command prompt from $ to >>.
After using the source command, the command line displays the new command prompt.

What happens when you type this command?

echo $HOME

The HOME variable is an environment variable that displays the path of the home directory. Here by typing echo $HOME, the terminal displays the path /home/ccuser as output.

You can customize the HOME variable if needed, but in most cases this is not necessary.


PATH
/home/ccuser/.gem/ruby/2.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin
/bin/ls
artists hello.txt
$


What happens when you type this command?

PATH

/home/ccuser/.gem/ruby/2.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin

PATH is an environment variable that stores a list of directories separated by a colon. Looking carefully, echo $PATH lists the following directories:

/home/ccuser/.gem/ruby/2.0.0/bin
/usr/local/sbin
/usr/local/bin
/usr/bin
/usr/sbin
/sbin
/bin
Each directory contains scripts for the command line to execute. The PATH variable simply lists which directories contain scripts.

For example, many commands we've learned are scripts stored in the /bin directory.

/bin/pwd

This is the script that is executed when you type the pwd command.

/bin/ls

This is the script that is executed when you type the ls command.

In advanced cases, you can customize the PATH variable when adding scripts of your own.



HOME=/home/ccuser
SHLVL=1
UPSTART_INSTANCE=
UPSTART_JOB=godex
_=/usr/bin/env
env | grep PATH
PATH=/home/ccuser/.gem/ruby/2.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbi
n:/sbin:/bin
$


What happens when you type this command?

env

The env command stands for "environment", and returns a list of the environment variables for the current user. Here, the env command returns a number of variables, including PATH, PWD, PS1, and HOME.

env | grep PATH

env | grep PATH is a command that displays the value of a single environment variable. Here the standard output of env is "piped" to the grep command. grep searches for the value of the variable PATH and outputs it to the terminal.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注