As we know, application servers mostly run the Linux operating system, which differs in many ways from Windows, familiar to almost everyone. Finding your way around the world of the penguin is not easy for everybody, and inexperienced people react differently to having to deal with it. Some take the attitude that it is a chance to learn something, others are paralyzed with fear that every mistake of theirs will have serious consequences. Still others fear nothing and do not read the documentation, so those serious consequences really do show up later.

Even so, every now and then we try to convince you that Linux and the server environment are really not that hard at a basic level, and that knowing even the fundamentals is genuinely useful. It is knowledge you can use not only at work but also in home projects or when trying to understand more complex problems, which gives you a chance to grow. Sometimes all you need is the ability to move around folders, run a script, restart a service, copy a file and do other operations that take little effort to learn, yet already let you achieve a lot.

Sometimes, though, you need a bit more, and that is what we will cover today. We will look at a few commands that may not be intuitive at first or are complex enough that people do not always remember their syntax and have to look it up in the documentation or on forums. At the same time, these are not operations reserved for administrators, because you can hardly call packing files or sending them from a server to a local computer that. But you do not run them every day, so they have not stuck in memory, and sometimes they simply come in handy. Today we will briefly go through a few such commands, focusing firmly on practice and therefore simplifying many aspects. Note that you can practice many of the points below on Windows with WSL, for example.

Packing and unpacking files

Surprisingly often, handling archive files on the command line causes trouble. It is true that you have to remember a particular order of parameters or switches, or keep checking the manual. Still, it is worth learning or jotting down next to your monitor, because when copying a large number of files to or from a server it really pays to do it as archived packages. Anyone who often copies thousands of files this way knows what I mean.

We most often meet two formats: .zip and .tar.gz (or .tgz, also called a tarball). The first is more convenient, but it requires the zip and unzip programs to be installed on the server, and they are not always available. The commands for the second format are available everywhere, although the shape of the command is less intuitive at first glance.

The syntax of the zip command is, in general, zip [options] file_name.zip files_to_pack. In the simplest case, to pack all the files in the current folder, we do it like this:

zip test.zip *

Of course, instead of the asterisk we can give specific files or folders separated by spaces, but note that in the latter case you need the -r option, which means searching subfolders recursively.

zip -r test.zip a.txt dir

Commands that pack everything except specific items, and ones that pack with a password (after running the command you will be asked to enter it), can also be useful.

zip -r test.zip * -x fileToIgnore.txt -x dirWithContentToIgnore/*
zip -e test.zip *

To unpack such an archive, the simplest way is to run unzip test.zip, but this creates the contents in the same folder you are currently in (not necessarily where the file itself is). To state the target directory explicitly, use the -d switch:

unzip test.zip -d folderDoRozpakowania

That is how it looks for the .zip extension. And what about .tar.gz (.tgz)? Below are all the commands above, this time in the tarball version:

tar cvfz test.tar.gz *
tar cvfz test.tar.gz a.txt dir # zwróćcie uwagę, że nie trzeba używać "-r" przy folderach
tar --exclude fileToIgnore.txt --exclude dirWithContentToIgnore cvfz test.tar.gz *
tar xvfz test.tar.gz
tar xvfz test.tar.gz -C folderDoRozpakowania # uwaga: folder musi wcześniej istnieć

A problem appears when you try to protect an archive with a password, because a tarball has no such built-in option. You can then encrypt the file with the GPG tool and the command gpg -c test.tar.gz.gpg test.tar.gz.

It is also worth explaining what those strange symbols in the tar command mean. Here is an explanation of the individual options:

  • c: create an archive.
  • x: extract an archive.
  • z: use Gunzip, that is, turn the .tar into a .tar.gz archive that uses compression.
  • v: short for verbose, that is, print a log of the operation, including the files being processed.
  • f: give the name of the file with the created archive.

Transferring files with SCP

In most cases, when we want to upload files to a server reachable over SSH or, conversely, download them from it, we use graphical programs like WinSCP or terminals with a GUI, such as MobaXterm. Sometimes, however, that is not possible or becomes much harder because of the particular way you reach the server. In that case some people do not really know how to get the files across. Sometimes they try to download from an external source with wget, others simply retype the content or paste it into an editor (by the way, in many terminals it is enough to select text to copy it and press the right mouse button to paste it). But there is a simpler way: meet the scp command.

Like ssh, scp connects over port 22, but it is not for logging in or running a command remotely. scp lets you transfer files between such a server and our machine, or another server. The structure is simple:

scp ścieżka/do/pliku user@serwer:folder/na/serwerze
scp user@serwer:folder/na/serwerze/plik ścieżka/do/folderu

In the first case we send a file to the server, in the second we download from it. Let us look at a practical example where our user on the server is "ubuntu", the IP address is 192.168.100.31, and we want to put the file "plik.txt" in the home folder, in the "backup" subdirectory. We assume this folder already exists.

scp plik.txt ubuntu@192.168.100.31:~/backup

That is all. We can send whole folders this way too, as long as we do not forget the -r switch.

scp -r folder/* ubuntu@192.168.100.31:~/backup

It works the same way when we want to download a file to our disk. Here it will be "plik.txt", which we save locally as "plik_z_serwera.txt".

scp ubuntu@192.168.100.31:~/backup/plik.txt plik_z_serwera.txt

You have surely noticed that the order of the arguments is key: first comes the place the file or folder is sent from, and second the recipient. If one of these points is an external server, you need to give the user, the "@" sign, the server address (a domain name or an IP), and then, after a colon, the path you are interested in. Note that the path has to exist on the server and, what is more, the terminal will not suggest it when you press the TAB key. Also, if connecting to the server requires giving the private key explicitly (-i klucz.key), we have to add that to the scp command too, just as we would with ssh.

Checking disk space

Server machines offer a certain amount of disk space, which can fill up, obviously. The problem appears when space suddenly runs out and you need to quickly see what takes so much, to win back a few megabytes. These are usually crisis situations (for example, a client reports that they cannot log in to the application or upload any file), and if we do not know how to do it right, we will struggle a bit. I am skipping the standard listing of files in a folder with their size and more using ls -l. It gives us some picture of the situation, but only for that one directory.

We will be more interested in the df -H command, which shows the size of individual disks, free and used space, and the percentage used. This makes it easy to tell whether space has run out: if "Use%" on the main disk is 100%, you need to get rid of something or add capacity. The command's name comes from "disk free" and "human readable". You can also change the last parameter to "-h" to show values divided by 1024 rather than 1000.

It is worth noting that df focuses on partitions, which is not particularly useful when we want to find out which folder takes up so much space. Then we lean toward the du command, which, run in the right folder, lists all subfolders and files with their sizes. Unfortunately, it does so in a very unreadable form, and with a large number of files we simply get an endless printout that prevents a quick reaction apart from the CTRL + C combination.

That is why it is even more worth remembering this command:

du -h --max-depth 1

It prints disk usage not only in a shortened format (although when comparing numbers it is sometimes better to drop the "-h" switch) but also only for the next subfolders at a specific depth. This means that if the folder we are in contains directories X, Y and Z, X contains X1 and X2, and Y contains Y1 and Y2, we will see only the usage of X, Y and Z. In short, on this basis we can judge which folder is worth analyzing further because it is the largest.

As you probably guess, changing the --max-depth parameter from 1 to 2, 3 and so on will deepen the information about individual subfolders. On the other hand, setting this attribute to 0 or switching to -s (du -hs) shows only the total usage of the whole folder, which can also be useful at times. It resembles opening "Properties" on a directory in Windows: we see the total size, including its subfolders and files.

It is also worth noting that adding the --time option gives us the time of the last modification of a given file or folder, and that we can point to the folder we want to measure by hand, since we are not limited to the directory we are currently in.

du -h --max-depth 1 --time innyFolder

Searching for files and their contents (find and grep)

Searching for something on disk is often needed, especially if we land on a machine where we have no idea what is where, such as a server with an application built by another team. Just as often we are interested not in the file but in its contents, because we know that something we are looking for is in there (for example, the database access configuration). How do we cope then? Most people know that the find and grep commands exist, but using them sometimes causes trouble.

Say we are in a directory where we want to find all files with the .xlsx extension. How do we do it?

find . -name '*.xlsx'

After the command name we give the location where we want to start searching. In our case it is a dot, that is, the current directory. If we have no idea where something is, we would probably put a slash (/) here, but we must realize that the search can take a very long time.

Next come the criteria. Ours is -name (note the single dash), followed by a name template using a pattern. Of course, if we know the exact file name, we can try typing it directly, without any asterisks standing in for any string of characters. The -name parameter is not the only option. As you probably expect, you can search by whether it is a file or a folder (-type), ignore letter case (-iname), take into account the time of the last modification (-mtime -numberofdays), and also, among other things, the size (-size). There are many possibilities, and the conditions themselves can be combined, including as alternatives. You will find lots of information and practical examples at this link.

One more small remark: when searching the whole file system we will often run into messages like "permission denied". That is understandable, since we usually do not have permission to read every folder, so while searching them Linux dutifully informs us that we cannot look inside, and that is that. If there are quite a lot of such messages, it can be tiring, but there is a way to get rid of them. For this you can use the "empty file" /dev/null (which, by the way, sometimes appears in IT memes) and redirect the so-called error output to it. I realize that for some this sounds like black magic, but explaining it fully would require covering the topic of standard streams, and that is not the goal of this text. For more information, I refer you to this page.

find / -name '*.xlsx' -print 2>/dev/null

However, we will probably more often want to search the contents of files with the grep command. Let us start with a simple case. Suppose we want to find the word "zadanie" ("task") in a specific file and we do not care about letter case. We then use the command:

grep -i 'zadanie' plik.txt

Note that even if the word "zadanie" appears as part of another string, it will still be found. If we do not want that, we should use the -w switch. Also remember that the tool searches the text content of files, so you will not find strings in binary files this way.

Now let us search the "arkusze" ("spreadsheets") folder for the string "Ania", printing the file and the line number:

grep -rn 'Ania' arkusze

If a command returns the contents of a file (for example, cat), we can also use it as the basis for searching those contents, using so-called pipes:

cat /proc/cpuinfo | grep -i 'Model'

With both commands discussed here, there may be so many results that they are hard to fit on the screen. In that case it is worth redirecting the result to a file:

grep -rn 'Ania' arkusze > output.txt

You will find a great many examples of using the grep command at this link.

Deleting files older than X days

Since we are on the subject of searching for files by various criteria, it is worth mentioning the option of deleting the ones that are found. At this point some will point out that files are deleted with the rm command, but it does not quite let us give all the parameters we need. Fortunately, the find we just covered comes to the rescue. Let us see how to delete all files with an SQL database backup older than 100 days.

find backups/ -name "backup_*.sql" -type f -mtime +100 -delete

The key here is the -mtime parameter, which filters files by age (we assume that making a backup is also its last modification), and the -delete parameter. I hardly need to say that because this command is so powerful, you should be very careful when running it.

Displaying part of a file

Sometimes we want to display a whole file. The cat command does that, simply showing the contents on the screen. Example:

cat plik.txt

The problem, however, is that with a very long text our terminal will simply be "flooded" by it. This can be solved in various ways, for example by replacing cat with more or less, which let you scroll through the file and browse it gradually. This is also useful for files so long that they challenge the stability of the system (although Vim is handy here as well). Another equally useful command for long content is tail, which displays the last N lines. An example for 50 lines:

tail -n 50 /var/log/apache2/error.log

Using a log file in the example is no accident: in logs we are most often interested in the last lines, when looking for an error that has just occurred.

List of running processes

Sometimes we want to check which processes are running on the server, for example to make sure a given job has started and is running. In its basic form we can use the ps command, but in many cases it is not enough, and it is worth adding three more switches to make ps alx. In such a list we can see not only the commands being executed but also, among other things, the PID (process ID) and the status (for example, whether it is running or stopped).

There is also an option that shows the percentage of CPU and memory use as well. ps aux may help here, but top is more interesting. The latter has the great feature of showing the process list dynamically, letting you watch how it changes over time. This can be very interesting when investigating the server's performance problems or operations that block it. You leave this window by pressing the "q" key. And if someone needs something a bit prettier, they can additionally install htop.

Suppose there is a process that disrupts the system and we want to end it in the most brutal way, by sending the KILL signal, also available under code 9. To do that, we need to know the PID of the task, which we can read with one of the previous commands. Knowing that the process we care about has PID 6789, we can run:

kill -9 6789

There are, however, situations where the problem involves many similar processes with the same name. An example is the PHP interpreter that started 40 times and in every case hung or deadlocked. Then we care less about the PID than about the process name and the killall command. For example, to stop php-fpm it would be:

killall -9 php-fpm

Of course, in this case too, you need to be extremely careful.

Checking active ports

Sometimes we want to see which ports our server listens on, to confirm that a network service has started. Contrary to appearances, this seemingly simple task can cause some trouble because it behaves slightly differently on different systems. Most often you can verify it with:

netstat -anp tcp

which shows all processes running on TCP ports with the port numbers and whether they are listening. With a long list you can use the grep command mentioned earlier:

netstat -anp tcp | grep LISTEN

And to make the task easier, you can always try to detect open ports from the outside with suitable programs or telnet.

Summary

We have by no means exhausted the topic. I also realize that Linux system administrators look at this article with distaste, because they do such things, and even harder ones, every day with their eyes closed. Still, we know that these things are not obvious to everyone and that such cheat sheets are sometimes needed. We do not always have graphical tools and interfaces that do part of the work for us, and sometimes the command line becomes the only way. So it is worth getting to know it and ceasing to be afraid of it. And along the way you develop your knowledge of Unix systems, which certainly will not hurt an IT person and may come in handy.

Best regards and thank you, Jakub Rojek.