37 Important Linux Commands You Should Know

Linux terminal on laptop with stylized textfatmawati achmad zaenuri / Shutterstock.com

Are you new to Linux or are you just a bit rusty? Here are all the commands you need to know. Consider this as an essential reference for the Linux terminal. This also applies to the macOS command line.

The essential toolkit for the terminal

Linux includes a large number of commands, but we chose 37 of the most important to present here. Learn these commands and you will be much more at home at the Linux command prompt.

The list below is presented in alphabetical order. The position of an order in the list is not representative of its usefulness or its simplicity. For the last word on using a command, refer to its manual pages. The man command is of course in our list – it's "manual".

1. alias

The alias command allows you to give your own name to a command or sequence of commands. You can then type your short name and the shell will execute the command or sequence of commands for you.

alias cls = clear

This creates an alias called cls. This will be another name for clear. When you type cls, the screen will be erased as if you had typed clear. Your alias records a few keystrokes, of course. However, if you frequently switch from one Windows command line to another, you may end up typing the Windows key command on a Linux machine that does not know what you mean. Now he will know.

Aliases can be much more complex than this simple example. Here is an alias called pf (to find a process) which is just a bit more complex. Note the use of quotation marks around the sequence of commands. This is necessary if the command sequence contains spaces. This alias uses the ps command to list the processes in progress, then pipes them via the grep command. The grep command looks for entries in the output of ps corresponding to the $ 1 command line parameter.

alias pf = "ps -e | grep $ 1"

If you want to discover the process ID (PID) of the shutter process – or find out if the shutter was even running – you can use the aliases of this way. Type pf, a space and the name of the process you are interested in:

pf shutter

Alias ​​command in the terminal window

The aliases defined on the command line will disappear with the terminal window. When you close it, they are gone. To keep your aliases always available, add them to the .bash_aliases file in your home directory.

2. cat

The cat (abbreviation of "concatenate") command lists the contents of the files in the terminal window. It's faster than opening the file in an editor and there is no chance that you accidentally modify the file. To read the contents of your .bash_log_out file, type the following command while the home directory is your current working directory, as is the case by default:

cat .bash_logout

Command cat .bash_logout in a terminal window

With files longer than the number of lines in your terminal window, the text will scroll too fast for you to read. You can channel cat output by less to make the process easier to manage. With less, you can scroll the file back and forth using the up and down arrow keys, the PgUp and PgDn keys, as well as the Start and End keys. Type q to exit less.

chat .bashrc | less

chat .bashrc | Less in a terminal window

3. cd

The cd command changes your current directory. In other words, it moves you to a new location in the file system.

If you move to a directory that is in your current directory, you can simply type cd and the name of the other directory.

cd work

If you change directories in the file system tree, specify the directory path with a /.

cd / usr / local / bin

To quickly return to your home directory, use the ~ (tilde) character as the directory name.

cd ~

Cd command in a terminal window

Here is another tip: you can use the double dot symbol to represent the parent of the current directory. You can type the following command to mount a directory:

cd ..

Imagine that you are in a directory. The parent directory contains other directories, as well as the one you are in. To switch to one of these directories, you can use the symbol .. to shorten what you need to type.

cd ../games

Cd command with .. in a terminal window

4. chmod

The chmod command sets the file authorization flags on a file or folder. The indicators define who can read, write, or execute the file. When listing files with the -l (long format) option, a string similar to this one appears.

-rwxrwxrwx

If the first character is a – the item is a file, if it is one of the item is a directory. The rest of the chain consists of three sets of three characters. On the left, the first three represent the owner's file permissions, the three center represent the file permissions of the group, and the last three characters on the right represent the permissions for the others. In each set, an r corresponds to a reading, an w to a writing, and an x ​​to an execution.

If the character r, w, or x is present, the file permission is granted. If the letter is not present and one – appears instead, this file permission is not granted.

One way to use chmod is to provide the permissions you want to give the owner, group, and others as a 3-digit number. The leftmost digit represents the owner. The middle number represents the group. The rightmost number represents the others. The numbers you can use and what they represent are listed here:

0: No authorization
1: Run permission
2: Permission to write
3: Write and execute permissions
4: Read permission
5: Read and execute permissions
6: Read and write permissions
7: Read, Write and Execute Permissions

Looking at our example.txt file, we can see that all three character sets are rwx. This means that everyone has the rights to read, write, and execute on the file.

To set the read, write, and execute permission (7 on our list) for the owner; read and write (6 on our list) for the group; and read and execute (5 in our list) for others, we will have to use the 765 digits with the chmod command:

chmod -R 765 example.txt

Chmod command in a terminal window

To set the permissions to read, write and run (7 in our list) for the owner, and read and write (6 in our list) for the group and for others, we would need to use 766 numbers with the chmod order:

chmod 766 example.txt

5. chown

The chown command allows you to change the owner and owner of the group of a file. By listing our example.txt file with ls -l, we can see Dave Dave in the description of the file. The first of these indicates the name of the owner of the file, which in this case is the dave user. The second entry shows that the name of the group owner is also dave. Each user has a default group created when it was created. This user is the only member of this group. This shows that the file is not shared with any other group of users.

You can use chown to change the owner, group or both of a file. You must provide the name of the owner and the group, separated by a character :. You will have to use sudo. To keep Dave as the owner of the file but to set Mary as the owner of the group, use this command:

sudo chown dave: mary example.txt

chown command in a terminal window

To change the owner and owner of the group to mary, use the following command;

sudo chown mary: mary example.txt

To change the file so that dave is the owner of the file and the owner of the group again, use this command:

sudo chown dave: dave example.txt

6. loop

The curl command is a tool for retrieving information and files from URLs or Internet addresses.

The curl command may not be part of your Linux distribution. Use apt-get to install this package on your system if you are using Ubuntu or another Debian-based distribution. On other Linux distributions, use the package management tool of your Linux distribution instead.

sudo apt-get install curl

Suppose you want to recover a single file from a GitHub repository. There is no way officially supported for this. You have to clone the entire repository. With curl however, we can recover the file we want by itself.

This command retrieves the file for us. Note that you must specify the name of the file in which you want to save it, using the -o (output) option. If you do not, the contents of the file will scroll quickly in the terminal window but will not be saved on your computer.

curl https://raw.githubusercontent.com/torvalds/linux/master/kernel/events/core.c -o core.c

If you do not want to see download progress information, use the -s (silent) option.

curl -s https://raw.githubusercontent.com/torvalds/linux/master/kernel/events/core.c -o core.c

curl in a terminal window

7. df

The df command shows the size, the space used and the available space on the mounted file systems of your computer.

The -h (human-readable) and -x (exclude) options are two of the most useful options. The human-readable option displays sizes in MB or GB instead of bytes. The exclusion option allows you to tell df to reduce file systems that do not interest you. For example, the pseudo-squashfs file systems created during the installation of an application using the snap command.

df -h -x squashfs

df command in a terminal window

RELATED: How to view available disk space and disk usage from the Linux terminal

8. diff

The diff command compare two text files and shows the differences between them. There are many options to adapt the display to your needs.

The -y (side-by-side) option displays line differences side by side. The -w (width) option allows you to specify the maximum line width to use to avoid wraparound lines. Both files are named alpha1.txt and alpha2.txt in this example. The –suppress-common-lines prevent diff from listing matching lines, allowing you to focus on lines that have differences.

diff -y -W 70 alpha1.txt alpha2.txt –suppress-common-lines

diff command in a terminal window

RELATED: How to compare two text files in the Linux terminal

9. echo

The echo command prints (echo) a text string in the terminal window.

The command below will print the words "A text string" in the terminal window.

echo A text string

The echo command can display the value of the environment variables, for example the $ USER, $ HOME, and $ PATH environment variables. They contain the values ​​of the user name, the home directory of the user and the search path for the corresponding commands when the user types something on the command line.

echo $ USER
echo $ HOME
echo $ PATH

echo command in a terminal window

The following command will cause a beep to sound. The -e option (escape code) interprets the escaped character as a bell character.

echo -e " a"

The echo command is also valuable in shell scripts. A script can use this command to generate a visible output indicating the progress or results of the script as it is executed.

10. exit

The exit command closes a terminal window, ends the execution of a shell script, or disconnects you from an SSH remote access session.

exit

exit command in a terminal window

11. find

Use the find command to locate files that you know exist if you do not remember where you placed them. You have to say where to start the search and what to look for. In this example, the. corresponds to the current folder and the -name option tells find to find the files whose name matches the search pattern.

You can use wildcards, where * represents any sequence of characters and? represents any character. We use * uns * to match any file name containing the sequence "ones". This would correspond to words like bones, stones and lonely.

find . -name * ones *

find command in a terminal window

As can be seen, find returned a list of matches. One of them is a repertoire called Ramones. We can say find to limit the search to files only. We do this using the -type option with the f parameter. The f parameter represents the files.

find . -type f -name * ones *

If you want the search to be case insensitive, use the -iname option.

find . -iname * wild *

12. finger

The finger command gives a brief information about a user, including the time of the last login of the user, the user 's home directory and the full name of the user' s account. user.

finger command in a terminal window

13. free

The free command gives you a summary of the memory usage with your computer. This applies to both random access memory (RAM) and the memory of exchange. The -h (human) option is used to provide user-friendly numbers and units. Without this option, the numbers are presented in bytes.

free -h

free command in a terminal window

14. grep

The grep utility looks for lines containing a search pattern. When we looked at the alias command, we used grep to look in the output of another program, ps. The grep command can also search for the contents of the files. Here we search for the word "train" in all the text files of the current directory.

grep train * .txt

The output lists the file name and displays the corresponding lines. The corresponding text is highlighted.

Grep command in a terminal window

The functionality and the great utility of grep justify your verification. his manual page.

15. groups

The groups command tells you which groups a user is a member of.

dave groups
mary groups

group control in a terminal window

16. gzip

The gzip command compresses the files. By default, it deletes the original file and leaves you with the compressed version. To keep both the original version and the compressed version, use the -k (keep) option.

gzip -k core.c

Gzip command in a terminal window

17. head

The command head gives you a list of the first 10 lines of a file. If you want to see fewer rows or more, use the -n (number) option. In this example, we use head with its default value of 10 lines. We then repeat the command by requesting only five lines.

head -core.c
head -n 5 core.c

main command in a terminal window

18. history

The history command lists the commands you previously issued on the command line. You can repeat any order in your history by typing an exclamation point! and the order number from the history list.

! 188

History command in a terminal window

Entering two exclamation points repeats your previous command.

!!

19. kill

The kill command allows you to terminate a process from the command line. You do this by providing the process ID (PID) of the process to kill. Do not kill the process willy-nilly. You must have a good reason to do it. In this example, we will act as if the shutter program is stuck.

To find the PID of the shutter, we will use our ps and grep tips from the section about the alias command above. We can search the shutter process and get its PID as follows:

ps -e | grep shutter.

Once we have determined the PID (1692 in this case), we can kill it as follows:

kill 1692

Kill command in a terminal window

20. less

The less command allows you to view files without opening an editor. Its use is faster and there is no chance that you will inadvertently modify the file. With less, you can scroll the file back and forth using the up and down arrow keys, the PgUp and PgDn keys, and the Start and End keys. Press the Q key to exit less.

To view a file, give its name to less as follows:

less core.c

less order in a terminal window

You can also direct the output of other commands to less. To see the output of ls for a list of your entire hard disk, use the following command:

ls -R / | less

less order in a terminal window

Use / to search forward in the file and use? look back.

21. ls

This could be the first command encountered by the majority of Linux users. It lists the files and folders in the directory that you specify. By default, search in the current directory. There are many options that you can use with ls, and we strongly recommend that you review its the manual page. Some common examples are presented here.

To list the files and folders in the current directory:

ls

To list the files and folders in the current directory with a detailed list, use the -l (long) option:

ls -l

To use user-friendly file sizes, include the -h (human) option:

ls -lh

To include hidden files, use the -a option (all files):

ls -lha

Ls command in a terminal window

22. man

The man command displays the "man pages" for one less command. The manual pages are the manual for using this command. Since man uses less to display the man pages, you can use the search functions of less.

For example, to see the chown man pages, use the following command:

chown man

Use the up and down arrows or the PgUp and PgDn keys to scroll through the document. Press q to exit the manual page or press h for help.

man command in a terminal window

23. mkdir

The mkdir command allows you to create new directories in the file system. You must supply the name of the new directory to mkdir. If the new directory is not in the current directory, you must specify the path to the new directory.

To create two new directories in the current directory, called "invoices" and "quotes", use these two commands:

mkdir bills
mkdir quotes

Mkdir command in a terminal window

To create a new directory called "2019" in the "Invoices" directory, use this command:

invoices mkdir / 2109

If you plan to create a directory, but its parent directory does not exist, you can use the -p option (parents) so that mkdir also creates all the required parent directories. In the following command, we create the directory "2019" in the "annual" directory in the "quotes" directory. The "annual" directory does not exist, but we can ask mkdir to create all the specified directories at once:

mkdir -p quotes / annual / 2019

The "annual" directory is also created.

24. mv

The mv command lets you move files and directories from one directory to another. It also allows you to rename files.

To move a file, you must tell mv where the file is and where you want to move it. In this example, we move a file named apache.pdf from the directory "~ / Document / Ukulele" and place it in the current directory, represented by the single file. character.

mv ~ / Documents / Ukulele / Apache.pdf.

Mv command in a terminal window

To rename the file, you "move" it to a new file with the new name.

mv Apache.pdf The_Shadows_Apache.pdf

The action of moving and renaming file could have been done in one step:

mv ~ / Documents / Ukulele / Apache.pdf ./The_Shadows_Apache.pdf

25. passwd

The passwd command allows you to change the password of a user. Just type passwd to change your own password.

You can also change the password of another user account, but you must use sudo. You will be prompted to enter the new password twice.

sudo passwd mary

passwd command in a terminal window

26. ping

The ping command allows you to verify that you have network connectivity with another network device. It is commonly used to solve network problems. To use ping, specify the IP address or the computer name of the other device.

ping 192.168.4.18

The ping command will run until you stop it with Ctrl + C.

ping in a terminal window

Here is what happens here:

The device at the 192.168.4.18 IP address responds to our ping requests and returns packets of 64 bytes.
the Internet Control Messaging Protocol Sequence numbering (ICMP) allows us to check for missing responses (lost packets).
TTL is the "life time" for a package. Whenever the packet goes through a router, it is (supposed to be) decremented by one. If it reaches zero, the package is discarded. The goal is to prevent network loopback problems from flooding the network.
The time value is the length of the round trip from your computer to the device. In simple terms, the lower this time, the better.

To ping a specific number of ping attempts, use the -c (number) option.

ping -c 5 192.168.4.18

To hear a ping, use the -a (audible) option.

ping -a 192.168.4.18

27. ps

The ps command lists the processes that are running. Using ps without any option causes the list of processes running in the current shell.

ps

ps command in a terminal window

To see all processes related to a particular user, use the -u (user) option. The list will probably be long, too, for convenience, use fewer resources.

ps -u dave | less

ps command in a terminal window

To see each process running, use the -e option (each process):

ps -e | less

28. pwd

Nice and simple, the pwd command prints the working directory (the current directory) from the root directory /.

pwd

pwd command in a terminal window

29. stop

The stop command allows you to stop or restart your Linux system.

The use of shutdown without settings will turn off your computer in a minute.

to close

stop command in a terminal window

To stop immediately, use the now parameter.

stop now

stop now

You can also schedule a stop and notify all connected users of the impending shutdown. For the shutdown command to know when you want to shut it down, you give it a time. This can be a set number of minutes from now, such as +90 or a specific time, such as 23:00. Any text messages you provide will be broadcast to connected users.

shutdown 23:00 Stop tonight at 23:00, save your work and disconnect before!

closing 23:00 with message

To cancel a stop, use the -c (cancel) option. Here we scheduled a stop in 15 minutes and then changed our mind.

stop +15 Stop in 15 minutes!
stop -c

Stop command -c cancel

RELATED: How to restart or stop Linux using the command line

30. SSH

Use the ssh command to connect to a remote Linux computer and log in to your account. To establish a connection, you must provide your user name and the IP address or domain name of the remote computer. In this example, the user Mary logs on to the computer at the address 192.168.4.23. Once the connection is established, he is asked for his password.

ssh mary@192.168.4.23

Ssh command in a terminal window

Her username and password are verified and accepted and she is logged in. Note that his invitation went from "Nostromo" to "howtogeek".

Mary launches the w command to list current users on the "howtogeek" system. It is listed as being connected from pts / 1, which is a pseudo-terminal slave. In other words, it is not a terminal directly connected to the computer.

To close the session, Mary's types come out and are returned to the shell on the "Nostromo" computer.

w
exit

w and leave the commands in a terminal window

31. sudo

The sudo command is required for operations requiring root or superuser permissions, such as changing another user's password.

sudo passwd mary

passwd command in a terminal window

32. tail

The tail command gives you a list of the last 10 lines of a file. If you want to see fewer rows or more, use the -n (number) option. In this example, we use tail with its default value of 10 lines. We then repeat the command by requesting only five lines.

tail core.c
tail -n 5 core.c

queue command in a terminal window

33. tar

With the tar command, you can create an archive file (also called tarball) that can contain many other files. This makes it much more convenient to distribute a collection of files. You can also use tar to extract the files from an archive file. It is common to ask tar to compress the archive. If you do not request compression, the archive file is created uncompressed.

To create an archive file, you must tell tar the files to include in the archive file and the name you want to assign to it.

In this example, the user will archive all the files in the Ukulele directory, which is in the current directory.

Ls command in the terminal window

They used the -c (create) option and the -v (verbose) option. The verbose option gives some visual information by listing the files in the terminal window as and when they are added to the archive. The -f option (file name) is followed by the desired name for the archive. In this case, it is songs.tar.

tar -cvf songs.tar Ukulele /

tar -cvf command in a terminal window

The files are listed in the terminal window as they are added to the archive file.

There are two ways to tell tar that you want the archive file to be compressed. The first is with the -z (gzip) option. This tells tar to use the gzip utility to compress the archive once it is created.

It is usual to add ".gz" as a suffix to this type of archive. This allows anyone who extracts files to know which commands to pass to tar to properly recover files.

tar -cvzf songs.tar.gz Ukulele /

tar -cvzf command in a terminal window

Les fichiers sont répertoriés dans la fenêtre du terminal au fur et à mesure qu'ils sont ajoutés au fichier d'archive comme auparavant, mais la création de l'archive prendra un peu plus de temps en raison du temps nécessaire à la compression.

Pour créer un fichier archive compressé à l'aide d'un algorithme de compression supérieur donnant un fichier archive plus petit, utilisez l'option -j (bzip2).

tar -cvjf songs.tar.bz2 Ukulele /

commande tar -cvjf dans une fenêtre de terminal

Une fois encore, les fichiers sont répertoriés lors de la création de l'archive. L'option -j est visiblement plus lente que l'option -z.

Si vous archivez un grand nombre de fichiers, vous devez choisir entre l'option -z pour une compression correcte et une vitesse raisonnable, ou l'option -j pour une meilleure compression et une vitesse plus lente.

Comme on peut le voir dans la capture d'écran ci-dessous, le fichier “.tar” est le plus gros, le “.tar.gz” est plus petit et le “.tar.bz2” est le plus petit des archives.

Commande ls dans une fenêtre de terminal

Pour extraire des fichiers d’un fichier d’archive, utilisez l’option -x (extraire). Les options -v (verbose) et -f (nomfichier) se comportent comme lors de la création d'archives. Utilisez ls pour confirmer le type d'archive à partir duquel vous allez extraire les fichiers, puis lancez la commande suivante.

ls
tar -xvf songs.tar

Commandes ls et tar -xvf dans une fenêtre de terminal

Les fichiers sont répertoriés au fur et à mesure de leur extraction. Notez que le répertoire Ukulele est également recréé pour vous.

Pour extraire des fichiers d’une archive «.tar.gz», utilisez l’option -z (gzip).

tar -xvzf songs.tar.gz

commande tar -xvzf dans une fenêtre de terminal

Enfin, pour extraire des fichiers d’une archive «.tar.bz2», utilisez l’option -j au lieu de l’option -z (gzip).

tar -xvjf songs.tar.bz2

commande tar -xvjf dans une fenêtre de terminal

RELATED: Comment extraire des fichiers d'un fichier .tar.gz ou .tar.bz2 sous Linux

34. top

La commande top vous montre un affichage en temps réel des données relatives à votre machine Linux. Le haut de l'écran est un résumé de l'état.

La première ligne indique le temps et la durée d'utilisation de votre ordinateur, le nombre d'utilisateurs connectés et la charge moyenne enregistrée au cours des 15 dernières minutes.

La deuxième ligne indique le nombre de tâches et leurs états: en cours d'exécution, arrêté, en veille et zombie.

La troisième ligne affiche les informations sur la CPU. Voici ce que signifient les champs:

us: la valeur est le temps CPU que le CPU consacre à l'exécution de processus pour les utilisateurs, en "espace utilisateur"
sy: valeur représente le temps CPU nécessaire à l'exécution des processus «espace noyau» du système.
ni: valeur représente le temps CPU nécessaire à l'exécution de processus avec une valeur de transaction définie manuellement
id: est la durée d'inactivité du processeur
wa: la valeur est la durée pendant laquelle la CPU attend la fin des E / S
salut: le temps passé par le processeur à traiter les interruptions matérielles
si: le temps passé par le processeur à traiter les interruptions logicielles
st: temps processeur perdu en raison de l'exécution de machines virtuelles («temps de vol»)

La quatrième ligne indique la quantité totale de mémoire physique, ainsi que la quantité de mémoire libre, utilisée, en mémoire tampon ou mise en cache.

La cinquième ligne indique la quantité totale de mémoire d'échange, ainsi que la quantité disponible, utilisée et disponible (compte tenu de la mémoire qui devrait être récupérable à partir de caches).

commande supérieure dans une fenêtre de terminal

L’utilisateur a appuyé sur la touche E pour modifier l’affichage en chiffres plus compréhensibles par l’homme au lieu d’entiers longs représentant des octets.

Les colonnes de l'écran principal sont constituées de:

PID: ID de processus
USER: Nom du propriétaire du processus
PR: Processus prioritaire
NI: La belle valeur du processus
VIRT: mémoire virtuelle utilisée par le processus
RES: Mémoire résidente utilisée par le processus
SHR: mémoire partagée utilisée par le processus
S: Statut du processus. Voir la liste ci-dessous des valeurs que ce champ peut prendre
% CPU: la part de temps CPU utilisée par le processus depuis la dernière mise à jour
% MEM: part de la mémoire physique utilisée
TIME +: temps CPU total utilisé par la tâche en centièmes de seconde
COMMANDE: nom de la commande ou ligne de commande (nom + options)

(La colonne de commande ne rentre pas dans la capture d'écran.)

Le statut du processus peut être l'un des suivants:

D: sommeil sans interruption
R: en cours d'exécution
S: dormir
T: tracé (arrêté)
Z: Zombie

Appuyez sur la touche Q pour sortir du haut.

RELATED: Comment définir les priorités de processus avec nice et Linux sur Linux

35. uname

Vous pouvez obtenir des informations système sur l’ordinateur Linux sur lequel vous travaillez avec la commande uname.

Utilisez l'option -a (tout) pour tout voir.
Utilisez l'option -s (nom du noyau) pour voir le type de noyau.
Utilisez l'option -r (version du noyau) pour afficher la version du noyau.
Utilisez l'option -v (version du noyau) pour afficher la version du noyau.
uname -a
uname -s
uname -r
uname -v

Commande uname dans une fenêtre de terminal

36. w

La commande w répertorie les utilisateurs actuellement connectés.

w

Commande w dans une fenêtre de terminal

37. whoami

Utilisez whoami pour savoir pour qui vous êtes connecté ou qui est connecté à un terminal Linux sans pilote.

who am I

Commande whoami dans une fenêtre de terminal

RELATED: Comment déterminer le compte d'utilisateur actuel sous Linux

C’est votre boîte à outils

Apprendre Linux, c'est comme apprendre autre chose. Vous allez avoir besoin de pratique avant de vous familiariser avec ces commandes. Une fois que vous avez ces commandes à portée de main, vous serez sur la voie de la maîtrise.

Il y a une vieille blague, probablement aussi vieille que Unix lui-même – qui dit que la seule commande que vous devez savoir est la commande homme. Il y a là une lueur de vérité, mais certaines pages de manuel sont impénétrables sans introduction. Ce tutoriel devrait vous donner l’introduction dont vous avez besoin.

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.