Managing Files and Directories
local graph
Chapter 5 — Managing Files and Directories
Section titled “Chapter 5 — Managing Files and Directories”In Chapter 4, Navigating and Essential Commands, we started looking deeper into Linux commands. We went over the most essential commands and covered the filesystem layout, as well as various methods to view the contents of files. In this chapter (as well as the next), we’ll continue to expand on the command line and become more efficient while using the terminal. This time around, we’ll expand a bit further on file management, take a look at input/output streams, and we’ll also develop an understanding of symbolic links. Along the way, we will cover:
- Copying, moving, and renaming files and directories
- Editing files with the Nano and Vim text editors
- Input and output streams
- Using symbolic and hard links
Let’s begin the chapter by taking a look at some methods we can use to alter the files and directories in the filesystem, such as copying and moving them.
Copying, moving, and renaming files and directories
Section titled “Copying, moving, and renaming files and directories”At this point, you should know how to move around within the filesystem (commands such as cd), inspect the contents of directories (ls), and even how to create empty files (the touch command). We even know how to remove files as well, such as executing the rm command against a file or directory. But until now, we haven’t looked at moving files around within your Ubuntu filesystem.
First, to make a copy of a file or directory, we use the cp command. Copying a file is fairly easy, and such a command would look similar to the following:
cp file1 file2In that example, file2 is created as an exact copy of file1. Copying a file is useful in many situations, some of the most common of which are:
- Copying a file to a backup medium, such as an external drive or network share
- Creating a copy of a file before making a change, such as before editing a very important text file
- Duplicating a log file for a point-in-time analysis
Let’s look at the last bullet point as another good example. We can capture a copy of the system log and store it in our current working directory by executing the following command:
sudo cp /var/log/syslog /home/<username>/syslogThe cp command is fairly simple: we give it a path to a file to copy, and then we type the path to the destination and desired filename. We also use sudo due to the fact that the syslog may not be readable by normal users by default, depending on the configuration. In the case of this command, a copy of the original syslog file will be saved in your current working directory.
For this particular example, log files are constantly being written to. It can sometimes be hard to troubleshoot an issue that occurred during a certain time if the file is continually expanding. That’s not the only reason though. We certainly wouldn’t want to make an accidental change to the log file and risk contaminating it or losing important information.
The previous command can actually be simplified a bit:
sudo cp /var/log/syslog .In that example, we removed the target path and name and replaced it with a period. The reason this works is that the period represents our current working directory. This isn’t specific to the cp command either. There actually is a directory named with a period in every directory, which is essentially a pointer to the current directory. Therefore, if you’re already inside the directory you want the file to be copied to, you don’t have to type the path. You don’t have to type the name either if you want the name of the file to be the same as the source.
Copying files (as well as moving them, which we’ll look at next) is potentially destructive. If the target path and name already exist, then the target will be overwritten. By default, you won’t see a confirmation before the target file is overwritten. As with all commands, take care that you really want to do whatever it is you’re telling the command-line interpreter to do.
When it comes to copying directories, the cp command by itself won’t do the trick:
sudo cp /var/log/apt .The /var/log/apt directory contains log files that keep track of transactions performed with the apt command. It can be useful to keep an eye on what your other admins are installing. When it comes to this example though, the previous command will fail with the following error:
cp: -r not specified; omitting directory '/var/log/apt'The error literally tells you what to do about it, and essentially the error is telling you that directories are omitted by default. In order to copy directories, you’ll need to include the -r option. This stands for recursive, which is an option you’ll see as a possibility for a handful of Linux commands. It tells the command-line interpreter to not only grab the object at the path you specified but to do so recursively and include child objects as well. Therefore, the following command will work:
sudo cp -r /var/log/apt .With that command, a local copy of the /var/log/apt directory will be stored in your current working directory, along with the contents.
When it comes to moving a file or directory from one place to another, we use the mv command. The syntax is almost exactly the same as the cp command. The difference is that instead of copying a file or directory, we’re moving it. In that regard, it’s probably self-explanatory how it works. Consider the following example commands:
mv file1 /path/to/new/directory/file1mv file1 file2With the first example, we’re assuming that file1 is in our current working directory. We’re grabbing that file and moving it to /path/to/new/directory and giving it the same name of file1 in that new directory. Just like with the cp command, we could’ve omitted the filename at the target, since it’s staying the same. If the file already exists in the target directory with that name, it will be overwritten. So, the mv command is also potentially destructive, but more so when compared to cp since you are moving, instead of copying.
The second mv command is a bit more interesting, because in that example we’re renaming a file. In Linux, there’s no dedicated rename command, so the mv command is used for that purpose. In fact, mv is somewhat of a Swiss Army knife due to the fact it serves multiple purposes. With it, you can move a file or directory, rename it, and also move a file to overwrite another file in a different location. It all depends on the source and destination paths. If the target exists, it will be overwritten. If not, the file will be renamed and/or moved to that path.
When managing files, you’ll certainly come to a situation where you need to manage multiple files or directories. It’s worth noting that the cp command, as well as the mv command, can be used with multiple objects at once; for example, if you have three directories, such as dir1, dir2, and dir3, and you need to move them into a new sub-directory. You could execute three mv commands to move each one separately, but you can also move all three with a single mv command:
mv dir1 dir2 dir3 /path/to/new/locationThe same holds true with cp and with files; both cp and mv are set up to allow you to move or copy multiple directories or files with a single command.
Now that we know how to move files around, we should also take a look at how to edit them. There are many text editors available to us on the Ubuntu platform, with Nano and Vim being among the most common. In the next section, we’ll go over the basics of both.
Editing files with the Nano and Vim text editors
Section titled “Editing files with the Nano and Vim text editors”Now that we know how to copy and move files, it would be useful to know how to edit them. There are multiple forms of text editors for Ubuntu, some available in the command line, and others in graphical environments such as the text editor in the desktop version.
Some may feel that command-line text editors are more complicated than Graphical User Interface (GUI) editors (and to be honest, they can be), but the main benefit is that you can use the same editor regardless of whether or not you have a GUI. In a way, this means the non-graphical editors are a bit more portable, and you can rely on them more. Almost all installations of Ubuntu will include the nano text editor, and you can rely on that more often than something like a particular GUI editor being available. In addition, the vim editor is another popular consideration. It’s a bit more advanced than nano, but in my opinion, much more powerful. In the following sections, we’ll look at both nano and vim.
Editing with Nano
Section titled “Editing with Nano”The nano editor, while more basic in terms of features, still has a fairly strong following. Actually, if you haven’t already noticed, a person’s choice of editor can cause somewhat of a debate in the Linux community. To launch the nano editor, it’s as simple as running the nano command. If you don’t provide nano with a filename, it simply starts with an empty window, as shown in the following screenshot:

Figure 5.1: The nano text editor, with no file selected
You can start typing right away, and when you want to save the file, you can simply press Ctrl + o to do so. On the bottom of the nano screen, you’ll see an overview of shortcuts, including the method for saving the file I just mentioned (which it refers to as Write Out). As you can see then*, Ctrl + x* is how you exit the editor and go back to the command line.
One trick that I love (which also works well with vim) is pressing t and then z while holding Ctrl when you have nano open, which will make it disappear. Normally, you don’t have to press Ctrl and t in order to background a process, but nano is the exception in this case.
Effectively, it’s the same as minimizing it. You can bring the nano window back by executing fg, which is short for foreground. The ability to background and foreground an application in the terminal is part of process management, which is actually something we’ll talk about in Chapter 7, Controlling and Managing Processes, but we’re giving you this tip ahead of time, to help you on your way! When it comes to editing files, sometimes it makes sense to send the editor to the background and bring it back later.
As you can probably guess, you can also use the nano command, with a target path and filename, to have the editor come up with a file already open. For example:
sudo nano /var/log/syslogThis command will result in the file opening in nano:

Figure 5.2: The nano text editor, with the syslog file open
To be fair, editing a log file directly is probably not a good idea in practice, but the example works. The syslog is a file you may want to open and inspect, but it would be a good idea to check the size of the syslog file with the ls -lh /var/log/syslog command to make sure it’s not excessively large in size, which can slow down the server.
All of that aside, the takeaway here is that you can open a file with nano directly by simply providing it with a path to something. Inside the editor window, you can move around with the arrow keys, just like you would in a graphical editor. You can also search for a specific string of text, by pressing Ctrl + w for Where Is, as is mentioned in the list of actions near the bottom.
In addition, note the text in the screenshot that is highlighted in red. It’s simply telling us that we don’t have access to edit the file. In that example, I didn’t use sudo because I didn’t intend on making any changes to the file.
Sometimes, I’ll open files in an editor that I don’t have write permission to make changes to, which serves as a fail-safe in case I accidentally do make a change (I won’t be able to save the file without sudo). To make a real change, I can close the file and reopen it with sudo.
Anyway, the nano editor is fairly simplistic. Is there more to it than that? Sure, but the most important thing to know is how to open files, edit them, and save them, which we’ve covered in this section. Of course, you can practice with the actions that are presented to you at the bottom of the window to go beyond normal usage.
Now, let’s take a look at Vim.
Editing with Vim
Section titled “Editing with Vim”Vim is my favorite editor, and the one I use most often. It’s a little on the advanced side, but it’s not to the point where it’s frustrating. By default, it’s not actually installed. Personally, I prefer the vim-nox package, which can be installed by executing the following command:
sudo apt install vim-noxIt really doesn’t matter which of the variations of vim you install. Each variation adds its own features. In the case of vim-nox, it has built-in support for scripting languages but is not really all that different from standard vim in other regards. The concepts you’ll learn here are not specific to this version. Just like nano, the vim editor can be called by itself by entering the command vim with no options, or with a path to a file, such as vim /home/myuser/myfile.txt. With no file chosen, vim will display its default help text. It gives you some of the default commands, such as :q for quitting the editor:

Figure 5.3: The vim text editor, with no file open
When you start vim, you start in command mode, which is one of several different modes the editor can be in. In command mode, you can’t actually edit text. Command mode allows you to run commands, as the name implies, which can allow you to manipulate text in really neat ways.
If you want to edit a file as you were already doing in nano, you’ll need to switch to insert mode to do so. You can switch to insert mode by pressing the Insert key on your keyboard, or the i letter key. Once you’re in insert mode, you can start typing as you normally would in any other editor. You’ll move the cursor around with the arrow keys, and insert text wherever you want. Outside of insert mode, you can also navigate with the h, j, k, and l keys in place of the arrow keys (which some users actually prefer). To exit insert mode, you can press Esc. That will bring you back to command mode.
At first, the different modes of vim can be a bit confusing to newcomers. For me, I see it as somewhat of a superpower. With vim, you have a mode for editing text and another dedicated mode for manipulating it. When it comes to text manipulation, that’s one of the strongest features of vim. For an example of this, consider the following hypothetical file:

Figure 5.4: The vim text editor, with a sample file
I don’t know why, but something about that file seems off to me. We’ll need to make a very important correction to try to fix it. First, you can see from the screenshot that the editor was left in insert mode. To do some text manipulation, we first need to press Esc to go back to command mode. Once there, we can get ready to type a command. And the command we want to type is this one:
:%s/Windows/Linux/gI don’t know about you, but personally, I think the file looks better now after running that command:

Figure 5.5: The vim text editor, after running a sample command
Technically, Linux is a kernel and not an operating system. Ubuntu, a distribution of Linux, is the closest equivalent of an operating system for us. But I’m willing to let that slide, for now. Other than that, in my opinion, this version of the file is more accurate!
This was a more advanced example of vim usage that would normally be outside the scope of this book. I wanted to show you an example of the power of this amazing editor, and finding and replacing text is just one of the many things we can do with it. Some people (including myself) even go as far as to install plugins to essentially turn vim into an Integrated Development Environment (IDE). In the example we’ve just used, we were able to find and replace all occurrences of a string with another string. This was also an example of the types of tasks we carry out in command mode, which allows us to manipulate text and enter more advanced commands. With this admittedly contrived example, you can immediately see the value of having multiple modes in vim.
I’ve been using vim for about a decade or so because I can never seem to figure out how to exit it. Okay, to be fair, that joke is getting to be a bit old now. If you’ve already been using Ubuntu or any other Linux distribution for a while, that joke probably made you cringe a little. If that was the first time you’ve seen it, then I’m glad I was the one that introduced you to it—for some reason, vim has a reputation for being difficult to exit. But that’s not really true at all, it’s actually quite easy. In command mode, you simply enter :q to exit the editor:
:qIf you’ve made changes, the :q command won’t let you exit, but you can force exit if you add an exclamation mark, so the command becomes :q!. If you’d also like to save changes while exiting, add w, so the command inside vim would become:
:wqEssentially, we’re exiting the editor (q) and writing the file at the same time (w). In command mode, commands start with a colon (:) and then the actual command. There are so many commands available that it’s impossible to talk about them all in one chapter. What I’ll do, then, is mention some that I consider to be the most important.
First, it’s actually possible to run a shell command without leaving vim by using the following command:
:! <shell command>The exclamation mark allows you to run a command, and then you type the actual command. For example:
:! ls -l /var/logThe previous example will show you the contents of the /var/log directory, and then you can press Enter to return back to vim. The :sp command is short for split:
:sp /path/to/fileIn this case, vim is able to show you more than one file at a time in the same window, effectively splitting the window to show you both files. With :split, or :sp for short (both do the same thing), it will either split the file into two views (the same file open in each) or it will show a separate file in the other split if you give it a filename. This command will split the file horizontally:

Figure 5.6: The vim text editor, with two files open in the same window
The previous screenshot shows two files open, /var/log/apt/history.log and /var/log/syslog. You may also notice that the status bar for each file, at the bottom, shows RO. As you can probably guess, this stands for read only and displays on the screen because I’m viewing files that only root has access to change, and I didn’t use sudo.
To switch between the two files, we can press the w key twice while holding Ctrl. When we do that, our insertion point moves from one split to the other. To exit each individual buffer (or the editor itself, if we only have one file open), we can press Esc to return to command mode, and then enter the :q or :q! command to exit without saving changes, or :wq to exit while also saving changes, just like before.
An alternative to :split is :vsplit, or :vs for short. It does the same thing as :split, but it splits the window vertically. Considering most computer displays nowadays are widescreen (and even ultra-widescreen), a vertical split often works out better in a practical sense:

Figure 5.7: The vim text editor, with two files open in a vertical split
To be honest, the effect doesn’t look all that great in the previous screenshot, the reason being the width of a page in a book isn’t enough to really show the benefit. Go ahead and give it a shot and see for yourself.
So far, we’ve gone over two modes of vim —command and insert mode. But there’s also another commonly used mode we haven’t discussed yet— visual mode. Visual mode allows you to select text, which then allows you to perform tasks such as copy and paste.
To do so, make sure you’re in command mode, and then start by moving the cursor to the first character in a series of text you want to copy. Then, press the v letter key on your keyboard, and move the selection with your arrow keys.
You’ll notice that you’ll highlight more text as you move the cursor. Once you’ve selected all the text that you’d like to copy, press the y key and the highlight will go away. At this point, you’ve essentially copied the text you had highlighted into the vim equivalent of the clipboard, similar to desktop operating systems. You can then (while also in command mode) press the p key to paste the text wherever the cursor is. It may take a few tries to get a hang of the workflow, but go ahead and give it a shot. If you make a mistake, you can press u while in command mode to undo, so you can revert any changes you make.
Again, vim is a somewhat advanced editor. Learning the basic functions is fairly easy, so knowing how to open, edit, close, and save files is something you can learn fairly quickly. The feature set of vim is so vast that I’m still learning new tricks many years after I started using it. To make sure you understand the basics though, let’s summarize the basic workflow of vim to help you memorize it. It looks something like this:
- Open Vim by either typing
vimby itself, or with a filename:vim <filename>. - You start in command mode. This mode is great for running
vimcommands. Press the Insert or the i key to switch to insert mode. - While in insert mode, you can edit the text by typing with your keyboard and moving the cursor around with the arrow keys.
- When you’re done editing the file, press Esc to return to command mode.
- To exit without saving changes, enter the
:qor:q!command. If you do want to save changes, enter:wby itself to save and remain in the editor, or:wqto save and quitvimat the same time.
Entire books could be written about vim (and there have been), so it would be outside the scope of this book to go into exhaustive detail. In fact, I even have a dedicated video tutorial series about it at www.learnlinux.tv if you’re interested in learning more. But for now, I’ll leave you with a few more useful tips that I think you should know.
While in command mode, you can press the x key to delete a single character, wherever the cursor is. You can press the d letter key twice in succession to delete an entire line. When you do this, that line is also copied into the paste buffer; you can paste that line by pressing p.
In addition, I mentioned several times that you can switch to insert mode by pressing i or Insert. You can also do so by pressing the a letter key with or without holding Shift. If you don’t hold Shift, you’ll enter insert mode one character to the right. This isn’t very useful to me, but typing a capital A is something I find myself doing a lot, which enters you into insert mode while also taking you to the very end of the current line. Since I often want to start typing after the end of a sentence, this works well for me.
Also, while in command mode, you can type Shift + g to immediately go to the very end of the file. Alternatively, you can press the g key twice in succession to move to the very top of the file.
Another trick I like is to turn on line numbers. This is useful, especially if an error message in a log file is complaining about a file regarding a specific line. The following command turns on line numbers:
:set numberThe following command disables line numbers:
:set nonumberIf you’d always like to see line numbers by default, you can edit the .vimrc file inside your home directory. This file is read by vim each time you start it.
Note that the .vimrc file begins with a period, which means that the file is hidden. Hidden files aren’t normally shown to you when you use ls to list the contents of a directory. Using the -a option with the ls command will show all files, including the ones that are normally hidden.
Go ahead and open the .vimrc file in your editor:
vim ~/.vimrcMost likely, this will be a blank file for you as a .vimrc file doesn’t exist by default. There are many commands we can add to tweak the behavior of the vim editor, too many to mention in a single chapter. The following line is very useful though, as it ensures that line numbers are enabled by default:
set numberLeaving out the colon at the beginning of the line is intentional; it’s not required inside the .vimrc file. From this point forward, each new vim session you open will start off with line numbers enabled. You can still disable line numbers as needed with the :set nonumber command within vim as we did earlier. In addition, you can add many more customizations to vim with the .vimrc file, but there are simply too many possibilities to mention here. For now, just know that customizing vim with the config file is something that you can do.
Now that we know how to edit files, we should also take a closer look at streams, which allow us to manipulate both input and output in various ways.
Input and output streams
Section titled “Input and output streams”During our journey into Ubuntu Server so far, we’ve worked quite a bit within the terminal. We’ve been able to inspect the contents of files, insert text into files, and more. We’ve actually been working with streams the entire time without knowing it. In this section, we’re going to talk about this subject in more detail.
If you’ve studied computer science at all, then you probably already know that output refers to things that are printed out of the computer (for example, text being printed to the screen, or onto paper from a printer) and input refers to data that is being entered into a computer, whether that be on the command line, into a file, or similar.
Linux takes this concept a bit further. Streams in Linux refer to a special way to handle what’s going in or out, and beyond the input and output streams, we also have a third that refers to errors.
Output streams in Linux are referred to as Standard Output, and input streams are referred to as Standard Input. These are abbreviated as stdout and stdin, respectively. The reason for the expansion of the simple concept of input/output into a concept of its own is because, on the Linux shell, we can handle these streams differently and perform different tasks with them.
We’ve been working with standard output throughout the entire book so far. Everything that is printed to the terminal is standard output. For example, when you ran the sudo apt install vim-nox command earlier, the results of that command (the flood of text showing the status of the package installation as it occurred) was standard output. When you use the cat /var/log/syslog command to have the contents of /var/log/syslog dumped onto the screen, the contents being displayed are standard output. By far, standard output is something you’ll work with the most.
To understand the concept of standard output better, let’s take a look at redirection. The following command is an example:
cat /var/log/syslog > ~/logfile.txtWith that command, we’re using cat to display the contents of /var/log/syslog. But instead of simply showing the contents onscreen we use the > character to redirect standard output into a file, ~/logfile.txt. This means that standard output (showing the contents of the file) will not be shown at all, since we redirected that into a file. Similarly, we could have also run:
cat /var/log/syslog 1> ~/logfile.txtNotice that I added a 1 right before the greater-than symbol. Standard output is designated by a file descriptor of 1. So, with that command, I’m specifically saying that I want to redirect standard output, and only standard output, into the file. Standard output is implied, so I didn’t need to include the 1. That’s why simply using the greater-than symbol works for redirecting standard output to a file.
If you want to append a file rather than completely overwrite it, you can use two greater-than symbols (>>) to append, rather than overwrite. For example, the following command will add the contents of the syslog file to the end of the logfile.txt file, rather than overwrite the entire file:
cat /var/log/syslog >> ~/logfile.txtStandard input also has a file descriptor, which is 0. Standard input is how commands receive data. Essentially, commands that accept input from the user do so by accepting stdin. Standard input is a bit more challenging to show in an example, but the following works:
cat /var/log/syslog | grep -i <keyword>With that command, I’m grabbing the contents of the /var/log/syslog file and piping that into the grep command, which allows me to display only the lines that include a specific term. No two syslog files will be the same, since every server can be configured uniquely. But if you’re attempting to investigate a specific application or service, you can grep the log for keywords you think might be appropriate. If you include the -i option, then grep will perform a search that’s case-insensitive. In this example, the output of the cat command becomes standard input to the grep command. This command can be executed with any search term of your choice.
I could have also run:
cat < /var/log/syslog | grep NetworkIn that example, I’m using the less-than symbol to redirect the contents of /var/log/syslog to be standard input to the cat command. The cat command normally prints whatever text is fed to it to the screen as standard output, but instead, I’m using the pipe symbol, |, to grab that output and use it as standard input to the grep command.
This concept can be a bit confusing at first, but if you keep practicing it, it will definitely make sense. Let’s look at another example, so we can understand standard error (stderr) as well:
find / -name "syslog"The find command allows you to find files that match particular criteria, such as looking for files that are named syslog in this example. Here, we’re searching the entire filesystem, because we used / to start the search from. The problem is I don’t have permission to read all the files on the filesystem, and I didn’t use sudo. This is going to result in quite a few errors being printed to the screen, errors such as these:
find: '/var/lib/netdata/health': Permission deniedfind: '/var/lib/netdata/registry': Permission deniedfind: '/var/lib/netdata/cloud.d': Permission deniedfind: '/var/lib/udisks2': Permission deniedSince the find command was used to search the entire filesystem, including places I don’t have permission to look, our terminal will be flooded with errors. These errors are displayed using standard error, which has a file descriptor of 2. If we want to hide these errors, we can do this:
find / -name "syslog" 2> /dev/nullWith that command, no errors will show up when we run it. That’s because we instructed the interpreter to capture standard error and redirect it to /dev/null. /dev/null is a special device where things disappear forever. If you move or redirect something there, it’s effectively deleted. Since a standard error has a file descriptor of 2, we combined that with the greater-than symbol to form 2>, which basically instructs the shell to do a redirect, but to only redirect standard error and leave standard output alone. We can also choose to redirect more than one stream to different places within a single command:
find / -name "syslog" 1> stdout.txt 2> stderr.txtWith that variation, I’m redirecting successful output to stdout.txt, and the errors to stderr.txt. This allows us full control over where successful and unsuccessful messages are printed. This also helps us quite a bit when it comes to troubleshooting, because we may want to focus on only the errors, and getting rid of the success output may trim the number of lines we’ll have to look through.
I recommend that you go ahead and practice this concept as much as you can; it’s definitely something you’ll want to commit to memory. You don’t have to master this concept right now, but knowing the basics will provide a great foundation.
Next, let’s discuss another aspect of file management—links. Sometimes, you’ll need to link one thing to another, and there are a few ways to go about that along with some best-practice advice.
Using symbolic and hard links
Section titled “Using symbolic and hard links”If you’ve used a graphical operating system for more than a week, you’re probably more than familiar with the concept of shortcuts. Either on the desktop or within a menu, you will have shortcuts to files and applications. This could be a shortcut to your home or profile directory, a shortcut to an application, an individual file, and so on. We have the same concept in Linux.
With Linux, we can link files to other files, which gives us the ability to create our own shortcuts, which are effectively similar to shortcuts in graphical operating systems, but without the requirement of a GUI. This comes in the form of symbolic and hard links, which are two different methods by which we can link things. Symbolic and hard links are very similar, but to explain them, you’ll first need to understand the concept of inodes.
An inode is a data object that contains metadata regarding files within your filesystem. Although a full walkthrough of the concept of inodes would be quite long, think of an inode as a type of database object, containing metadata for the actual items you’re storing on your disk. Information stored in inodes includes details such as the owner of the file, permissions, last modified date, and type (whether it is a directory or a file). Inodes are represented by an integer number, which you can view with the -i option of the ls command. On my system, I created two files: file1 and file2. These files are inodes 265416 and 266112, respectively. You can see this output in the following screenshot where I run the ls -i command. This information will come in handy shortly:

Figure 5.8: Output of ls -i
As I mentioned earlier, there are two types of links in Linux: the symbolic link and hard link. While the two types of links approach the concept differently, they pretty much serve the same purpose. Basically, a link allows us to reference a file somewhere else on our filesystem.
For a practical example, let’s create a hard link. In my case, I have a couple of files in a test directory, so I can create a link to either of them. To create a link, we’ll use the ln command:
ln file1 file3Here, I’m creating a hard link (file3) that is linked to file1. To play around with this, go ahead and create a link to a file on your system. If we use ls again with the -i option, we’ll see something interesting:

Figure 5.9: Output of second ls -I command
If you look closely at the output, both file1 and file3 have the same inode number. Essentially, a hard link is a duplicate directory entry, where both entries point to the same data. In this case, we created a hard link that points to another file. With this hard link created, we can move file3 into another location on the filesystem and it will still be a link to file1. Hard links have a couple of limitations, however. First, you cannot create a hard link to a directory, only a file. Second, this link cannot be moved to a different filesystem. That makes sense, considering each filesystem has its own inodes. Inode 265416 on my system would, of course, not point to the same file on another system, if this inode number even exists at all.
To overcome these limitations, we can consider using a soft link instead. A soft link (also known as a symbolic link or symlink) is an entry that points to another directory or file. This is different from a hard link because a hard link is a duplicate entry that references an inode, while a symbolic link references a specific path. Symbolic links can not only be moved around between filesystems; we can also create a symbolic link to a directory as well. To illustrate how a symbolic link works, let’s create one. In my case, I’ll delete file3 and recreate it as a symbolic link. We’ll again use the ln command:
rm file3ln -s file1 file3With the -s option of ln, I’m creating a symbolic link. First, I deleted the original hard link with the rm command (which doesn’t disturb the original file, file1) and then created a symbolic link, also named file3. If we use ls -i again, we’ll see that file3 does not have the same inode number as file1:

Figure 5.10: Output of ls -i after creating a symbolic link
Notice that the inode numbers of each file are all different. At this point, the main difference compared with a hard link should become apparent. A symbolic link is not a clone of the original file; it’s simply a pointer to the original file’s path. Any commands you execute against file3 are actually being run against the target that the link is pointing to. Hard links, on the other hand, point directly to the file.
In practice, symbolic links are incredibly useful when it comes to server administration. However, it’s important not to go crazy and create a great number of symbolic links all over the filesystem. This certainly won’t be a problem for you if you are the only administrator on the server, but if you resign and someone takes your place, it will be a headache for them to figure out all of your symbolic links and map where they lead to. You can certainly create documentation for your symbolic links, but then you’d have to keep track of them and constantly update documentation. My recommendation is to only create symbolic links when there are no other options, or if doing so benefits your organization and streamlines your file layout.
Getting back to the subject of symbolic links versus hard links, you’re probably wondering which you should use and when to use them. The main benefit of a hard link is that you can move either file (the link or the original) to anywhere on the same filesystem and the link will not break. This is not true of symbolic links; however, if you move the original file, the symbolic link will be pointing to a file that no longer exists at that location. Hard links are basically duplicate entries pointing to the same object, and thus have the same inode number, so both will have the same file size and content. A symbolic link is a pointer to the file’s path—nothing more, nothing less.
However, even though I just spoke about the several benefits of hard links, I actually recommend symbolic links for most use cases. They can cross filesystems, can be linked to directories, and it’s easier to determine from the output where they lead. If you move hard links around, you may forget where they were originally located or which file actually points to which. Sure, with a few commands you can find them and map them easily. But overall, symbolic links are more convenient in the long run. As long as you’re mindful of recreating your symbolic link whenever you move the original file (and you use them only when you need to), you shouldn’t have an issue.
Summary
Section titled “Summary”In this chapter, we elevated our terminal kung-fu to another level and looked at concepts such as moving and copying files. We continued into a discussion of two popular text editors, Nano and Vim. Then, we took a dive into the subject of streams, and finished off the chapter with an understanding of the differences between symbolic and hard links, as well as how to create them.
In Chapter 6,Boosting Your Command-line Efficiency, we’ll dive a bit deeper into command-line tips and tricks, which will include a discussion on Bash history, writing basic scripts, and more.
Relevant videos
Section titled “Relevant videos”- Linux Crash Course – Data Streams (LearnLinuxTV): https://linux.video/se-data-streams
- Linux Crash Course – nano (LearnLinuxTV): https://linux.video/le-nano
- Linux Crash Course – Symbolic Links (LearnLinuxTV): https://linux.video/se-symlinks
- Vim Text Editor Tutorial Series: https://learnlinux.link/vim