Working with Files and Directories

Overview:

  • Teaching: 30 min
  • Exercises: 20 min

Questions

  • How can I create, copy, and delete files and directories?
  • How can I edit files?

Objectives

  • Create a directory hierarchy that matches a given diagram.
  • Create files in that hierarchy using an editor or by copying and renaming existing files.
  • Delete, copy and move specified files and/or directories.

Creating directories

We now know how to explore files and directories, but how do we create them in the first place?

In this episode we will learn about creating and moving files and directories, using the IntroShell/data/shell-lesson-data/exercise-data/writing directory as an example.

We should still be in the shell-lesson-data directory on the Desktop, which we can check using:

jupyter-user:~$pwd
/jupyter/jupyter-user/IntroShell/data/shell-lesson-data

Now lets change to the exercise-data/writing directory:

jupyter-user:~$cd excercise-data/writing

Ans check what is in the directory:

jupyter-user:~$ls -F
LittleWomen.txt  haiku.txt

Create a directory

Let’s create a new directory called thesis using the command mkdir thesis (which will print no output):

jupyter-user:~$mkdir thesis

As you might guess from its name, mkdir means ‘make directory’. Since thesis is a relative path (i.e., does not have a leading slash, like /what/ever/thesis), the new directory is created in the current working directory:

jupyter-user:~$ls -F
LittleWomen.txt  haiku.txt thesis/

Since we’ve just created the thesis directory, there’s nothing in it yet:

jupyter-user:~$ls -F thesis

Note that mkdir is not limited to creating single directories one at a time. The -p option allows mkdir to create a directory with nested subdirectories in a single operation:

jupyter-user:~$mkdir -p ../project/data ../project/results

The -R option to the lscommand will list all nested subdirectories within a directory. Let’s use ls -FR to recursively list the new directory hierarchy we just created in the project directory:

jupyter-user:~$ls -FR ../project
../project/:
data/  results/

../project/data:

../project/results:

Two ways of doing the same thing

Using the shell to create a directory is no different than using a file explorer. If you open the current directory using your operating system's graphical file explorer, the thesis directory will appear there too. While they are two different ways of interacting with the files, the files and directories themselves are the same.

Good names for files and directories

Complicated names of files and directories can make your life painful when working on the command line. Here we provide a few useful tips for the names of your files and directories.

  • Don’t use spaces: Spaces can make a name more meaningful, but since spaces are used to separate arguments on the command line it is better to avoid them in names of files and directories. You can use - or _ instead (e.g. north-pacific-gyre/ rather than north pacific gyre/). To test this out, try typing mkdir north pacific gyreand see what directory (or directories!) are made when you check with ls -F.

  • Don’t begin the name with - (dash): Commands treat names starting with - as options.

  • Stick with letters, numbers, . (period or ‘full stop’), - (dash) and _ (underscore): Many other characters have special meanings on the command line. We will learn about some of these during this lesson. There are special characters that can cause your command to not work as expected and can even result in data loss.

If you need to refer to names of files or directories that have spaces or other special characters, you should surround the name in quotes ("").

Create a text file

Let’s change our working directory to thesis using cd, then run a text editor called Nano to create a file called draft.txt:

jupyter-user:~$cd thesis
jupyter-user:~$nano draft.txt

Which Editor?

When we say, "nano is a text editor," we really do mean "text": it can only work with plain character data, not tables, images, or any other human-friendly media. We use it in examples because it is one of the least complex text editors. However, because of this trait, it may not be powerful enough or flexible enough for the work you need to do after this workshop. On Unix systems (such as Linux and Mac OS X), many programmers use Emacs or Vim (both of which require more time to learn), or a graphical editor such as Gedit. On Windows, you may wish to use Notepad++. Windows also has a built-in editor called notepad that can be run from the command line in the same way as nano for the purposes of this lesson.

No matter what editor you use, you will need to know where it searches for and saves files. If you start it from the shell, it will (probably) use your current working directory as its default location. If you use your computer's start menu, it may want to save files in your desktop or documents directory instead. You can change this by navigating to another directory the first time you "Save As…"

Let's type in a few lines of text. Once we're happy with our text, we can press Ctrl-O (press the Ctrl or Control key and, while holding it down, press the O key) to write our data to disk (we'll be asked what file we want to save this to: press Return to accept the suggested default of draft.txt).

alttext

Once our file is saved, we can use Ctrl-X to quit the editor and return to the shell.

Control, Ctrl, or ^ Key

The Control key is also called the "Ctrl" key. There are various ways in which using the Control key may be described. For example, you may see an instruction to press the Control key and, while holding it down, press the X key, described as any of:

  • Control-X
  • Control+X
  • Ctrl-X
  • Ctrl+X
  • ^X
  • C-x In nano, along the bottom of the screen you'll see ^G Get Help ^O WriteOut. This means that you can use Control-G to get help and Control-O to save your file.

nano doesn't leave any output on the screen after it exits, but ls now shows that we have created a file called draft.txt:

Creating Files a Different Way

We have seen how to create text files using the nano editor. Now, try the following command in your home directory:

jupyter-user:~$cd                  # go to your home directory
jupyter-user:~$touch my_file.txt
  1. What did the touch command do? When you look at your home directory using the GUI file explorer, does the file show up?
  2. Use ls -l to inspect the files. How large is my_file.txt?
  3. When might you want to create a file this way?

Solution

Removing a file

Lets tidy up our home dirctory by removing the file we have just created:

jupyter-user:~$rm my_file.txt

The rm command removes files (rm is short for "remove"). If we run ls again, it tells us that our file is gone.

Deleting Is Forever

The Unix shell doesn't have a trash bin that we can recover deleted files from (though most graphical interfaces to Unix do). Instead, when we delete files, they are unhooked from the file system so that their storage space on disk can be recycled. Tools for finding and recovering deleted files do exist, but there's no guarantee they'll work in any particular situation, since the computer may recycle the file's disk space right away.

Lets move back to our writing directory:

jupyter-user:~$cd -
jupyter-user:~$pwd
/jupyter/jupyter-user/IntroShell/data/shell-lesson-data/exercise-data/writing

And remove the thesis folder we created:

jupyter-user:~$rm thesis
rm: cannot remove 'thesis': Is a directory

This happens because rm by default only works on files, not directories.

To really get rid of thesis we must also delete the file draft.txt. We can do this with the recursive option for rm:

jupyter-user:~$rm -r thesis

Recreate the thesis folder and draft.txt file again.

With Great Power Comes Great Responsibility

Removing the files in a directory recursively can be a very dangerous operation. If we're concerned about what we might be deleting we can add the "interactive" flag -i to rm which will ask us for confirmation before each step

jupyter-user:~$rm -r -i thesis
jupyter-user:~$rm: descend into directory 'thesis'? y
jupyter-user:~$rm: remove regular file 'thesis/draft.txt'? y
jupyter-user:~$rm: remove directory 'thesis'? y

This removes everything in the directory, then the directory itself, asking at each step for you to confirm the deletion. Recreate the folder and file once again (or select n when asked for confirmation above)

Moving files and directories

draft.txt isn't a particularly informative name, so let's change the file's name using mv, which is short for "move":

jupyter-user:~$mv thesis/draft.txt  thesis/quotes.txt

The first argument tells mv what we're "moving", while the second is where it's to go. In this case, we're moving thesis/draft.txt to thesis/quotes.txt, which has the same effect as renaming the file. Sure enough, ls shows us that thesis now contains one file called quotes.txt:

jupyter-user:~$ls thesis
quotes.txt

One has to be careful when specifying the target file name, since mv will silently overwrite any existing file with the same name, which could lead to data loss. An additional flag, mv -i (or mv --interactive), can be used to make mv ask you for confirmation before overwriting.

Just for the sake of consistency, mv also works on directories

Let's move quotes.txt into the current working directory. We use mv once again, but this time we'll just use the name of a directory as the second argument to tell mv that we want to keep the filename, but put the file somewhere new. (This is why the command is called "move".) In this case, the directory name we use is the special directory name . that we mentioned earlier.

The effect is to move the file from the directory it was in to the current working directory. ls now shows us that thesis is empty:

jupyter-user:~$ls thesis

Parameters and Arguments

According to Wikipedia, the terms argument and parameter mean slightly different things. In practice, however, most people use them interchangeably to refer to the input term(s) given to a command.

ls is the command, -F are the flags (also called options), and IntroShell/data is the argument.

Further, ls with a filename or directory name as an argument only lists that file or directory. We can use this to see that quotes.txt is still in our current directory:

jupyter-user:~$ls quotes.txt

Moving to the Current Folder

After running the following commands, Jamie realizes that she put the files sucrose.dat and maltose.dat into the wrong folder:

ls -F
analyzed/ raw/
ls -F analyzed
fructose.dat glucose.dat maltose.dat sucrose.dat
cd raw/

Fill in the blanks to move these files to the current folder (i.e., the one she is currently in):

mv ___/sucrose.dat  ___/maltose.dat ___

.

Solution

Copying files and Directories

The cp command works very much like mv, except it copies a file instead of moving it. We can check that it did the right thing using ls with two paths as arguments - like most Unix commands, ls can be given multiple paths at once:

jupyter-user:~$cp quotes.txt thesis/quotations.txt
jupyter-user:~$ls quotes.txt thesis/quotations.txt
quotes.txt  thesis/quotations.txt

To prove that we made a copy, let's delete the quotes.txt file in the current directory and then run that same ls again.

jupyter-user:~$rm quotes.txt 
jupyter-user:~$ls quotes.txt thesis/quotations.txt
ls: cannot access 'quotes.txt': No such file or directory
thesis/quotations.txt

We can also copy a directory and all its contents by using the recursive option -r, e.g. to back up a directory:

jupyter-user:~$cp -r thesis thesis_backup

and check the result by listing the contents of both the thesis and thesis_backup directories:

jupyter-user:~$ls thesis thesis_backup
thesis:
quotations.txt

thesis_backup/:
quotations.txt

Renaming Files

Suppose that you created a .txt file in your current directory to contain a list of the statistical tests you will need to do to analyze your data, and named it: statstics.txt

After creating and saving this file you realize you misspelled the filename! You want to correct the mistake, which of the following commands could you use to do so?

  1. cp statstics.txt statistics.txt
  2. mv statstics.txt statistics.txt
  3. mv statstics.txt .
  4. cp statstics.txt .

Solution

Moving and Copying

What is the output of the closing ls command in the sequence shown below?

pwd
/Users/jamie/data
ls
proteins.dat
mkdir recombine
mv proteins.dat recombine/
cp recombine/proteins.dat ../proteins-saved.dat
ls
  1. proteins-saved.dat recombine
  2. recombine
  3. proteins.dat recombine
  4. proteins-saved.dat

Copy with Multiple Filenames

For this exercise, you can test the commands in the IntroShell/data/shell-lesson-data/exercise-data directory.

In the example below, what does cp do when given several filenames and a directory name?

jupyter-user:~$mkdir backup
cp creatures/minotaur.dat creatures/unicorn.dat backup/

In the example below, what does cp do when given three or more file names?

jupyter-user:~$cd creatures
jupyter-user:~$ls -F
basilisk.dat  minotaur.dat  unicorn.dat
jupyter-user:~$cp minotaur.dat unicorn.dat basilisk.dat

.

Solution

Using wildcards for accessing multiple files at once

Wildcards

* is a wildcard. It matches zero or more characters, so *.pdb matches ethane.pdb, propane.pdb, and every file that ends with '.pdb'. On the other hand, p*.pdb only matches pentane.pdb and propane.pdb, because the 'p' at the front only matches filenames that begin with the letter 'p'.

? is also a wildcard, but it only matches a single character. This means that p?.pdb would match pi.pdb or p5.pdb (if we had these two files in the molecules directory), but not propane.pdb. We can use any number of wildcards at a time: for example, p*.p?* matches anything that starts with a 'p' and ends with '.', 'p', and at least one more character (since the ? has to match one character, and the final * can match any number of characters). Thus, p*.p?* would match preferred.practice, and even p.pi (since the first * can match no characters at all), but not quality.practice (doesn't start with 'p') or preferred.p (there isn't at least one character after the '.p').

When the shell sees a wildcard, it expands the wildcard to create a list of matching filenames before running the command that was asked for. As an exception, if a wildcard expression does not match any file, Bash will pass the expression as an argument to the command as it is. For example typing ls *.pdf in the molecules directory (which contains only files with names ending with .pdb) results in an error message that there is no file called *.pdf. However, generally commands like wc and ls see the lists of file names matching these expressions, but not the wildcards themselves. It is the shell, not the other programs, that deals with expanding wildcards.

Using Wildcards

Exercise: Using Wildcards

When run in the molecules directory, which ls command(s) will produce this output?

ethane.pdb methane.pdb
  • ls *t*ane.pdb
  • ls *t?ne.*
  • ls *t??ne.pdb
  • ls ethane.*

Solution

More on Wildcards

Sam has a directory containing calibration data, datasets, and descriptions of the datasets:

├── 2015-10-23-calibration.txt
├── 2015-10-23-dataset1.txt
├── 2015-10-23-dataset2.txt
├── 2015-10-23-dataset_overview.txt
├── 2015-10-26-calibration.txt
├── 2015-10-26-dataset1.txt
├── 2015-10-26-dataset2.txt
├── 2015-10-26-dataset_overview.txt
├── 2015-11-23-calibration.txt
├── 2015-11-23-dataset1.txt
├── 2015-11-23-dataset2.txt
├── 2015-11-23-dataset_overview.txt
├── backup
│   ├── calibration
│   └── datasets
└── send_to_bob
    ├── all_datasets_created_on_a_23rd
    └── all_november_files

Before heading off to another field trip, she wants to back up her data and send some datasets to her colleague Bob. Sam uses the following commands to get the job done:

$ cp *dataset* backup/datasets
$ cp ____calibration____ backup/calibration
$ cp 2015-____-____ send_to_bob/all_november_files/
$ cp ____ send_to_bob/all_datasets_created_on_a_23rd/

Help Sam by filling in the blanks.

The resulting structure should look like:

├── 2015-10-23-calibration.txt
├── 2015-10-23-dataset1.txt
├── 2015-10-23-dataset2.txt
├── 2015-10-23-dataset_overview.txt
├── 2015-10-26-calibration.txt
├── 2015-10-26-dataset1.txt
├── 2015-10-26-dataset2.txt
├── 2015-10-26-dataset_overview.txt
├── 2015-11-23-calibration.txt
├── 2015-11-23-dataset1.txt
├── 2015-11-23-dataset2.txt
├── 2015-11-23-dataset_overview.txt
├── backup
│   ├── calibration
│      ├── 2015-10-23-calibration.txt
│      ├── 2015-10-26-calibration.txt
│      └── 2015-11-23-calibration.txt
│   └── datasets
│       ├── 2015-10-23-dataset1.txt
│       ├── 2015-10-23-dataset2.txt
│       ├── 2015-10-23-dataset_overview.txt
│       ├── 2015-10-26-dataset1.txt
│       ├── 2015-10-26-dataset2.txt
│       ├── 2015-10-26-dataset_overview.txt
│       ├── 2015-11-23-dataset1.txt
│       ├── 2015-11-23-dataset2.txt
│       └── 2015-11-23-dataset_overview.txt
└── send_to_bob
    ├── all_datasets_created_on_a_23rd
       ├── 2015-10-23-dataset1.txt
       ├── 2015-10-23-dataset2.txt
       ├── 2015-10-23-dataset_overview.txt
       ├── 2015-11-23-dataset1.txt
       ├── 2015-11-23-dataset2.txt
       └── 2015-11-23-dataset_overview.txt
    └── all_november_files
        ├── 2015-11-23-calibration.txt
        ├── 2015-11-23-dataset1.txt
        ├── 2015-11-23-dataset2.txt
        └── 2015-11-23-dataset_overview.txt

Solution

Organizing Directories and Files

Jamie is working on a project and she sees that her files aren't very well organized:

ls -F
analyzed/  fructose.dat    raw/   sucrose.dat

The fructose.dat and sucrose.dat files contain output from her data analysis. What command(s) covered in this lesson does she need to run so that the commands below will produce the output shown?

ls -F
analyzed/   raw/
ls analyzed
fructose.dat    sucrose.dat

.

Solution

Reproduce a Folder Structure

You’re starting a new experiment and would like to duplicate the directory structure from your previous experiment so you can add new data.

Assume that the previous experiment is in a folder called 2016-05-18, which contains a data folder that in turn contains folders named raw and processed that contain data files. The goal is to copy the folder structure of the 2016-05-18 folder into a folder called 2016-05-20 so that your final directory structure looks like this:

2016-05-20/
└── data
   ├── processed
   └── raw

Which of the following set of commands would achieve this objective? What would the other commands do?

$ mkdir 2016-05-20
$ mkdir 2016-05-20/data
$ mkdir 2016-05-20/data/processed
$ mkdir 2016-05-20/data/raw
$ mkdir 2016-05-20
$ cd 2016-05-20
$ mkdir data
$ cd data
$ mkdir raw processed
$ mkdir 2016-05-20/data/raw
$ mkdir 2016-05-20/data/processed
$ mkdir -p 2016-05-20/data/raw
$ mkdir -p 2016-05-20/data/processed
$ mkdir 2016-05-20
$ cd 2016-05-20
$ mkdir data
$ mkdir raw processed

Solution

Key Points

  • cp old new copies a file.
  • mkdir path creates a new directory.
  • mv old new moves (renames) a file or directory.
  • rm path removes (deletes) a file.
  • * matches zero or more characters in a filename, so *.txt matches all files ending in .txt.
  • ? matches any single character in a filename, so ?.txt matches a.txt but not any.txt.
  • Use of the Control key may be described in many ways, including Ctrl-X, Control-X, and ^X.
  • The shell does not have a trash bin: once something is deleted, it's really gone.
  • Depending on the type of work you do, you may need a more powerful text editor than Nano.