Working With Files and Directories
Overview
Teaching: 20 min
Exercises: 10 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 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
and use ls -F
to see what it contains:
$ pwd
/home/username/data-shell
$ 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 mkdir thesis
(which has no output):
$ mkdir thesis
As you might guess from its name,
mkdir
means “make directory”.
Since 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
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.
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
-
or_
instead of whitespace.Don’t begin the name with
-
(dash).Commands treat names starting with
-
as options.Stick with letters, numbers,
.
(period),-
(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 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 thesis
using cd
,
then run a text editor called Nano to create a file called draft.txt
:
$ cd thesis
$ 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 Nano 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 callednotepad
that can be run from the command line in the same way asnano
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…”
Note: to use Nano on Magnus you must load the nano module using the following command:
module load nano
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
).
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 useControl-G
to get help andControl-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
:
$ ls
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:$ 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?
Use
ls -l
to inspect the files. How large ismy_file.txt
?When might you want to create a file this way?
Solution
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 data-shell
directory,
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 ls
again,
its output is empty once more,
which tells us that our file is gone:
$ ls
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 /home/username/data-shell
using cd ..
:
$ pwd
/home/username/data-shell/thesis
$ nano draft.txt
$ ls
draft.txt
$ cd ..
If we try to remove the entire thesis
directory using rm thesis
,
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 draft.txt
.
We can do this with the recursive option for rm
:
$ rm -r thesis
Using
rm
SafelyWhat happens when we type
rm -i thesis/quotations.txt
? Why would we want this protection when usingrm
?Solution
$ 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
-i
torm
which 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.
Horror stories
There are many rm -r horror stories including how the movie Toy Story 2 accidently got deleted and was only recovered from a Technical Director’s home computer. Story told via YouTube video
Let’s create that directory and file one more time.
$ pwd
/home/username/data-shell
$ mkdir thesis
$ cd thesis
$ nano draft.txt
$ ls
draft.txt
draft.txt
isn’t a particularly informative name,
so let’s change the file’s name using mv
,
which is short for “move”:
$ mv draft.txt 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 draft.txt
to 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
:
$ ls
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.
The cp
command works very much like mv
,
except it copies a file instead of moving it.
$ cp quotes.txt quotations.txt
To prove that we made a copy,
let’s run ls
again.
$ ls
quotes.txt quotations.txt
There should be two files. You can check each file has the same contents.
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 filemythesis
or 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:.txt
signals a plain text file,.cfg
is a configuration file full of parameters for some program or other,.png
is 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.mp3
doesn’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.
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?
cp statstics.txt statistics.txt
mv statstics.txt statistics.txt
mv statstics.txt .
cp statstics.txt .
Solution
- 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.
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
andsucrose.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
mv *.dat analyzed
Jamie needs to move her files
fructose.dat
andsucrose.dat
to theanalyzed
directory. The shell will expand *.dat to match all .dat files in the current directory. Themv
command then moves the list of .dat files to the “analyzed” directory.
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.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.
Most files’ names are
something.extension
. The extension isn’t required, and doesn’t guarantee anything, but is normally used to indicate the type of data in the file.