Working With Files and Directories
OverviewTeaching: 30 min
Exercises: 20 minQuestions
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.
We now know how to explore files and directories,
but how do we create them in the first place?
Let’s go back to our
data-shell directory on the Desktop
ls -F to see what it contains:
$ ls -F
creatures/ data/ molecules/ north-pacific-gyre/ notes.txt pizza.cfg solar.pdf writing/
Let’s create a new directory called
thesis using the command
(which has no output):
$ mkdir thesis
As you might guess from its name,
mkdir means “make directory”.
thesis is a relative path
(i.e., doesn’t have a leading slash),
the new directory is created in the current working directory:
$ ls -F
creatures/ data/ molecules/ north-pacific-gyre/ notes.txt pizza.cfg solar.pdf thesis/ writing/
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
thesisdirectory 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.
Don’t use whitespaces.
Whitespaces can make a name more meaningful but since whitespace is used to break arguments on the command line it is better to avoid them in names of files and directories. You can use
_instead of whitespace.
Don’t begin the name with
Commands treat names starting with
Stick with letters, numbers,
.(period or ‘full stop’),
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 whitespace or another non-alphanumeric character, you should surround the name in quotes (
Since we’ve just created the
thesis directory, there’s nothing in it yet:
$ ls -F thesis
Let’s change our working directory to
then run a text editor called Nano to create a file called
$ cd thesis $ nano draft.txt
When we say, “
nanois 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
notepadthat can be run from the command line in the same way as
nanofor 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
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:
In nano, along the bottom of the screen you’ll see
^G Get Help ^O WriteOut. This means that you can use
Control-Gto get help and
Control-Oto save your file.
nano doesn’t leave any output on the screen after it exits,
ls now shows that we have created a file called
Creating Files a Different Way
We have seen how to create text files using the
nanoeditor. Now, try the following command in your home directory:
$ cd # go to your home directory $ touch my_file.txt
What did the touch command do? When you look at your home directory using the GUI file explorer, does the file show up?
ls -lto inspect the files. How large is
When might you want to create a file this way?
The touch command generates a new file called ‘my_file.txt’ in your home directory. If you are in your home directory, you can observe this newly generated file by typing ‘ls’ at the command line prompt. ‘my_file.txt’ can also be viewed in your GUI file explorer.
When you inspect the file with ‘ls -l’, note that the size of ‘my_file.txt’ is 0kb. In other words, it contains no data. If you open ‘my_file.txt’ using your text editor it is blank.
Some programs do not generate output files themselves, but instead require that empty files have already been generated. When the program is run, it searches for an existing file to populate with its output. The touch command allows you to efficiently generate a blank text file to be used by such programs.
Returning to the
let’s tidy up the
thesis directory by removing the draft we created:
$ cd thesis $ rm draft.txt
This command removes files (
rm is short for “remove”).
If we run
its output is empty once more,
which 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.
Let’s re-create that file
and then move up one directory to
$ nano draft.txt $ ls
$ cd ..
If we try to remove the entire
thesis directory using
we get an error message:
$ 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
We can do this with the recursive option for
$ rm -r thesis
What happens when we type
rm -i thesis/quotations.txt? Why would we want this protection when using
$ rm: remove regular file 'thesis/quotations.txt'?
The -i option will prompt before every removal. The Unix shell doesn’t have a trash bin, so all the files removed will disappear forever. By using the -i flag, we have the chance to check that we are deleting only the files that we want to remove.
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
rmwhich will ask us for confirmation before each step
$ rm -r -i thesis rm: descend into directory ‘thesis’? y rm: remove regular file ‘thesis/draft.txt’? y 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.
Let’s create that directory and file one more time.
(Note that this time we’re running
nano with the path
rather than going into the
thesis directory and running
$ mkdir thesis $ nano thesis/draft.txt $ ls thesis
draft.txt isn’t a particularly informative name,
so let’s change the file’s name using
which is short for “move”:
$ 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,
which has the same effect as renaming the file.
ls shows us that
thesis now contains one file called
$ ls thesis
One has to be careful when specifying the target file name, since
silently overwrite any existing file with the same name, which could
lead to data loss. An additional flag,
mv -i (or
can be used to make
mv ask you for confirmation before overwriting.
Just for the sake of consistency,
mv also works on directories
quotes.txt into the current working directory.
mv once again,
but this time we’ll just use the name of a directory as the second argument
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.
$ mv thesis/quotes.txt .
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:
$ ls thesis
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:
$ ls quotes.txt
Moving to the Current Folder
After running the following commands, Jamie realizes that she put the files
maltose.datinto 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 ___
$ mv ../analyzed/sucrose.dat ../analyzed/maltose.dat .
..refers to the parent directory (i.e. one above the current directory) and that
.refers to the current directory.
cp command works very much like
except it copies a file instead of moving it.
We can check that it did the right thing using
with two paths as arguments — like most Unix commands,
ls can be given multiple paths at once:
$ cp quotes.txt thesis/quotations.txt $ ls 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
$ rm quotes.txt $ ls quotes.txt thesis/quotations.txt
ls: cannot access quotes.txt: No such file or directory thesis/quotations.txt
This time it tells us that it can’t find
quotes.txt in the current directory,
but it does find the copy in
thesis that we didn’t delete.
What’s In A Name?
You may have noticed that all of Nelle’s files’ names are “something dot something”, and in this part of the lesson, we always used the extension
.txt. This is just a convention: we can call a file
mythesisor almost anything else we want. However, most people use two-part names most of the time to help them (and their programs) tell different kinds of files apart. The second part of such a name is called the filename extension, and indicates what type of data the file holds:
.txtsignals a plain text file,
.cfgis a configuration file full of parameters for some program or other,
.pngis a PNG image, and so on.
This is just a convention, albeit an important one. Files contain bytes: it’s up to us and our programs to interpret those bytes according to the rules for plain text files, PDF documents, configuration files, images, and so on.
Naming a PNG image of a whale as
whale.mp3doesn’t somehow magically turn it into a recording of whalesong, though it might cause the operating system to try to open it with a music player when someone double-clicks it.
Suppose that you created a
.txtfile in your current directory to contain a list of the statistical tests you will need to do to analyze your data, and named it:
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?
cp statstics.txt statistics.txt
mv statstics.txt statistics.txt
mv statstics.txt .
cp statstics.txt .
- No. While this would create a file with the correct name, the incorrectly named file still exists in the directory and would need to be deleted.
- Yes, this would work to rename the file.
- No, the period(.) indicates where to move the file, but does not provide a new file name; identical file names cannot be created.
- No, the period(.) indicates where to copy the file, but does not provide a new file name; identical file names cannot be created.
Moving and Copying
What is the output of the closing
lscommand in the sequence shown below?
$ mkdir recombine $ mv proteins.dat recombine/ $ cp recombine/proteins.dat ../proteins-saved.dat $ ls
We start in the
/Users/jamie/datadirectory, and create a new folder called
recombine. The second line moves (
mv) the file
proteins.datto the new folder (
recombine). The third line makes a copy of the file we just moved. The tricky part here is where the file was copied to. Recall that
..means “go up a level”, so the copied file is now in
/Users/jamie. Notice that
..is interpreted with respect to the current working directory, not with respect to the location of the file being copied. So, the only thing that will show using ls (in
/Users/jamie/data) is the recombine folder.
- No, see explanation above.
proteins-saved.datis located at
- No, see explanation above.
proteins.datis located at
- No, see explanation above.
proteins-saved.datis located at
Copy with Multiple Filenames
For this exercise, you can test the commands in the
In the example below, what does
cpdo when given several filenames and a directory name?
$ mkdir backup $ cp amino-acids.txt animals.txt backup/
In the example below, what does
cpdo when given three or more file names?
$ ls -F
amino-acids.txt animals.txt backup/ elements/ morse.txt pdb/ planets.txt salmon.txt sunspot.txt
$ cp amino-acids.txt animals.txt morse.txt
If given more than one file name followed by a directory name (i.e. the destination directory must be the last argument),
cpcopies the files to the named directory.
If given three file names,
cpthrows an error because it is expecting a directory name as the last argument.
cp: target ‘morse.txt’ is not a directory
*is a wildcard. It matches zero or more characters, so
propane.pdb, and every file that ends with ‘.pdb’. On the other hand,
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
p5.pdb(if we had these two files in the
moleculesdirectory), 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,
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 *.pdfin the
moleculesdirectory (which contains only files with names ending with
.pdb) results in an error message that there is no file called
lssee 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, and this is another example of orthogonal design.
When run in the
lscommand(s) will produce this output?
The solution is
1.shows all files whose names contain zero or more characters (
*) followed by the letter
t, then zero or more characters (
*) followed by
ane.pdb. This gives
ethane.pdb methane.pdb octane.pdb pentane.pdb.
2.shows all files whose names start with zero or more characters (
*) followed by the letter
t, then a single character (
ne.followed by zero or more characters (
*). This will give us
pentane.pdbbut doesn’t match anything which ends in
3.fixes the problems of option 2 by matching two characters (
ne. This is the solution.
4.only shows files starting with
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
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.
$ cp *calibration.txt /backup/calibration $ cp 2015-11-* ~/send_to_bob/all_november_files/ $ cp *-23-dataset* ~send_to_bob/all_datasets_created_on_a_23rd/
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
sucrose.datfiles 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
$ ls analyzed
mv *.dat analyzed
Jamie needs to move her files
analyzeddirectory. The shell will expand *.dat to match all .dat files in the current directory. The
mvcommand then moves the list of .dat files to the “analyzed” directory.
Copy a folder structure but not the files
You’re starting a new experiment, and would like to duplicate the file structure from your previous experiment without the data files so you can add new data.
Assume that the file structure is in a folder called ‘2016-05-18-data’, which contains a
datafolder that in turn contains folders named
processedthat contain data files. The goal is to copy the file structure of the
2016-05-18-datafolder into a folder called
2016-05-20-dataand remove the data files from the directory you just created.
Which of the following set of commands would achieve this objective? What would the other commands do?
$ cp -r 2016-05-18-data/ 2016-05-20-data/ $ rm 2016-05-20-data/raw/* $ rm 2016-05-20-data/processed/*
$ rm 2016-05-20-data/raw/* $ rm 2016-05-20-data/processed/* $ cp -r 2016-05-18-data/ 2016-5-20-data/
$ cp -r 2016-05-18-data/ 2016-05-20-data/ $ rm -r -i 2016-05-20-data/
The first set of commands achieves this objective. First we have a recursive copy of a data folder. Then two
rmcommands which remove all files in the specified directories. The shell expands the ‘*’ wild card to match all files and subdirectories.
The second set of commands have the wrong order: attempting to delete files which haven’t yet been copied, followed by the recursive copy command which would copy them.
The third set of commands would achieve the objective, but in a time-consuming way: the first command copies the directory recursively, but the second command deletes interactively, prompting for confirmation for each file and directory.
cp old newcopies a file.
mkdir pathcreates a new directory.
mv old newmoves (renames) a file or directory.
rm pathremoves (deletes) a file.
*matches zero or more characters in a filename, so
*.txtmatches all files ending in
?matches any single character in a filename, so
Use of the Control key may be described in many ways, including
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.