Command Line Basics (Linux and macOS)
Working with Files and Pipes
In this lesson you will
- Read files with cat, head and less
- Copy, move and remove files carefully
- Combine commands with pipes and redirection
Introduction
Command line tools are small and do one job each. Their real power comes from combining them, like building with blocks.
Reading files
Terminal
$ cat notes.txt # print the whole file
$ head -n 3 notes.txt # first 3 lines
$ tail -n 3 notes.txt # last 3 lines
$ less notes.txt # scroll a long file; press q to quit
$ wc -l notes.txt # count the linesCopy, move, rename and delete
Terminal
$ cp notes.txt backup.txt # copy
$ mv backup.txt old.txt # move or rename
$ rm old.txt # remove (delete)
$ rm -r practice # remove a folder and everything insideWarning: rm does not use a recycle bin. Deleted files are gone. Double check the name before pressing Enter, and be especially careful with rm -r.
Quick quiz
Which command renames a file called a.txt to b.txt?
Redirection
Use > to send output into a file instead of the screen:
Terminal
$ echo "buy milk" > todo.txt # create or overwrite
$ echo "call mum" >> todo.txt # append to the end
$ cat todo.txt
buy milk
call mumBe careful: a single > replaces the file contents.
Pipes
The pipe | sends the output of one command into the next:
Terminal
$ ls | wc -l # how many items are in this folder?
$ cat todo.txt | sort # sort the lines
$ history | grep "git" # find earlier commands containing gitgrep searches text for a pattern. For example, grep "milk" todo.txt prints lines that contain the word milk.
Try it yourself
Create a file with three lines using echo and >>. Use sort to show them in order, and wc -l to count them. Then use grep to find one word.
Summary
cat,head,tail,lessandwcread files.cp,mvandrmcopy, move and delete, andrmis permanent.>and>>redirect output to files, and|connects commands together.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading