Please enable JavaScript to use CodeHS

Terminal & Bash — Tutorial 2

Files and Folders

Folders keep your work organized, and files hold your code, notes, and data. The terminal gives you quick commands to inspect, copy, move, and delete them. These commands are safer and faster than dragging with a mouse once you know what they do.

Files and folders

A computer stores information in files. Files live inside folders, also called directories. A folder can contain files and other folders. This tree structure is exactly what you see in a Finder or File Explorer window, only you access it through text commands.

A path tells the computer how to get to a file. If the path starts with /, it starts from the root of the whole machine. Otherwise it starts from where you are now.

Reading files with cat

The cat command prints a file's contents to the screen. Its real name is short for "concatenate," but programmers use it most often just to read. For long files, less opens a scrollable view.

  • cat file.txt — show the contents of file.txt.
  • head file.txt — show the first 10 lines.
  • tail file.txt — show the last 10 lines.

These commands do not change the file. They only read it.

Copy, move, and remove

Three commands change your files and folders:

  • cp old.txt new.txt — copy a file. You keep the original and get a duplicate.
  • mv old.txt folder/ — move a file or folder. It can also rename: mv old.txt new.txt.
  • rm file.txt — remove a file. There is no trash bin in the terminal, so be careful.

To remove an empty folder, use rmdir foldername. To remove a folder and everything inside it, use rm -r foldername. The -r stands for "recursive." Because it deletes folders and their contents, take an extra moment to check the path before pressing Enter.

Finding files

As your projects grow, you may not remember exactly where a file is. The find command searches through directories for you.

  • find . -name "report.txt" — search from the current folder downward for a file named report.txt.
  • find . -name "*.py" — find every file ending in .py.

The dot (.) means "start here." The asterisk is a wildcard that matches anything.

Try the terminal

Use the simulator below to practice. The home folder already contains a few files. Try reading them, copying them, and finding files by extension.

bash — ~/home

Check yourself

Create a new folder named backups in the home directory, copy welcome.txt into it, then rename the copy to old-welcome.txt. Finish by listing the contents of backups.

Be careful with rm -r and rm -rf. They delete immediately. Always double-check the path.

Quick quiz

1. What does cat do?

2. Which command renames a file?

3. What does find . -name '*.py' do?

Keep learning

You can read, copy, move, find, and delete files from the terminal. Next, learn how to chain commands together with pipes and filters.

Tutorial 2 of the “Terminal & Bash” series.