Current Linux systems have graphical utilities dedicated to the work of an administrator. However, it is important to be able to use the interface in command line mode for several reasons:
The majority of system commands are common to all Linux distributions, which is not the case for graphical tools.
It can happen that the system does not start correctly but that a backup command interpreter remains accessible.
Remote administration is done on the command line with an SSH terminal.
In order to preserve server resources, the graphical interface is either not installed or launched on demand.
Administration is done by scripts.
Learning these commands allows the administrator to connect to a Linux terminal, to manage its resources and files, to identify the station, the terminal, and the connected users, etc.
The user of a Linux system will be defined in the /etc/passwd file, by:
A login name, more commonly called "login", containing no spaces.
A numeric identifier: UID (User Identifier).
A group identifier: GID (Group Identifier).
A command interpreter, e.g., a shell, which can be different from one user to another.
A connection directory, e.g., the home directory.
In other files the user will be defined by:
A password, which is encrypted before being stored (/etc/shadow).
A command prompt, or prompt login, which is symbolized by a
# for administrators
and a $ for other users (/etc/profile).
Depending on the security policy implemented on the system, the password will require a certain number of characters and meet certain complexity requirements.
Among the existing command interpreters, the Bourne-Again Shell (/bin/bash) is the one most frequently used. It is assigned by default to new users. For various reasons, advanced Linux users can choose alternative shells such as the Korn Shell (ksh), the C Shell (csh), etc.
The user's login directory is by convention stored in the /home directory of the workstation. It will contain the user's personal data and the configuration files of his applications. By default, at login, the login directory is selected as the current directory.
A workstation-type installation (with graphical interface) starts this interface on terminal 1. Linux being multi-user, it is possible to connect several users several times, on different physical terminals (TTY) or virtual terminals (PTS). Virtual terminals are available within a graphical environment. A user switches from one physical terminal to another using Alt+Fx from the command line or using Ctrl+Alt+Fx.
Once the user is connected to a console, the shell displays the command prompt. It then behaves like an infinite loop, repeating the same pattern with each statement entered:
Displays the command prompt.
Reads the command.
Analyzes the syntax.
Substitutes special characters.
Executes the command.
Displays the command prompt.
Etc.
The key sequence Ctrl+C is used to interrupt a running command.
The use of a command generally follows this sequence:
command[option(s)][argument(s)]
The name of the command is often lower case.
A space separates each item.
Short options begin with a dash (-l), while long options begin with two dashes (--list).
A double dash (--) indicates the end of the option list.
It is possible to group some short options together:
ls-l-i-a
is equivalent to:
ls-lia
There can be several arguments after an option:
ls-lia/etc/home/var
In the literature, the term "option" is equivalent to the term "parameter," which is more commonly used in programming. The optional side of an option or argument is symbolized by enclosing it in square brackets [ and ]. When more than one option is possible, a vertical bar called a "pipe" separates them [a|e|i].
It is impossible for an administrator at any level to know all the commands and options in detail. A manual is usually available for all installed commands.
Once found by apropos or whatis, the manual is read by man ("Man is your friend").
This set of manuals is divided into 8 sections, grouping information by topic, the default section being 1:
Executable programs or commands.
System calls (functions given by the kernel).
Library calls (functions given by the library).
Special files (usually found in /dev).
File Formats and conventions (configuration files such as etc/passwd).
Games (such as character-based applications).
Miscellaneous (e.g. man (7)).
System administration commands (usually only for root).
Kernel routines (non-standard).
Information about each section can be accessed by typing man x intro, where x is the section number.
The command:
manpasswd
will tell the administrator about the passwd command, its options, etc. While a:
man5passwd
will inform him about the files related to the command.
Navigate through the manual with the arrows ↑ and ↓. Exit the manual by pressing the q key.
The clear command clears the contents of the terminal screen. More accurately, it shifts the display so that the command prompt is at the top of the screen on the first line.
On a physical terminal, the display will be permanently hidden, whereas in a graphical interface, a scrollbar will allow you to go back in the history of the virtual terminal.
Tip
CTRL + L will have the same effect as the clear command
For various reasons, the script developer may need to use special sequences (starting with a \ character). In this case, the -e option will be stipulated, allowing interpretation of the sequences.
Among the frequently used sequences, we can mention:
The id command is used to display information about users and groups. By default, no user parameter is added, and the information of the currently logged in user and group is displayed。
Since Linux is multi-user, it is possible that multiple sessions are open on the same station, either physically or over the network. It is interesting to know which users are logged in, if only to communicate with them by sending messages.
tty: represents a terminal.
pts/: represents a virtual console in a graphical environment with the number after representing the instance of the virtual console (0, 1, 2...)
The -r option also displays the runlevel (see chapter "startup").
In Linux, the file tree is an inverted tree, called a single hierarchical tree, whose root is the directory /.
The current directory is the directory where the user is located.
The connection directory is the working directory associated with the user. The login directories are, by default, stored in the /home directory.
When the user logs in, the current directory is the login directory.
An absolute path references a file from the root by traversing the entire tree to the file level:
/home/groupA/alice/file
The relative path references that same file by traversing the entire tree from the current directory:
../alice/file
In the above example, the ".." refers to the parent directory of the current directory.
A directory, even if it is empty, will necessarily contain at least two references:
.: reference to itself.
..: reference to the parent directory of the current directory.
A relative path can thus start with ./ or ../. When the relative path refers to a subdirectory or file in the current directory, then the ./ is often omitted. Mentioning the first ./ in the tree will only really be required to run an executable file.
Errors in paths can cause many problems: creating folders or files in the wrong places, unintentional deletions, etc. It is therefore strongly recommended to use auto-completion when entering paths.
In the above example, we are looking to give the location of the file myfile from the directory of bob.
By an absolute path, the current directory does not matter. We start at the root, and work our way down to the directories home, groupA, alice and finally the file myfile: /home/groupA/alice/myfile.
By a relative path, our starting point being the current directory bob, we go up one level through .. (i.e., into the groupA directory), then down into the alice directory, and finally the myfile file: ../alice/myfile.
The pwd (Print Working Directory) command displays the absolute path of the current directory.
$pwd
/home/rockstar
To use a relative path to reference a file or directory, or use the cd command to move to another directory, you must know its location in the file tree.
Depending on the type of shell and the different parameters of its configuration file, the terminal prompt (also known as the command prompt) will display the absolute or relative path of the current directory.
The ls command displays the contents of a directory.
ls[-a][-i][-l][directory1][directory2][…]
Example:
$ls/home
...rockstar
The main options of the ls command are:
Option
Information
-a
Displays all files, even hidden ones. Hidden files in Linux are those beginning with ..
-i
Displays inode numbers.
-l
Use a long listing format, that is, each line displays long format information for a file or directory.
The ls command, however, has a lot of options (see man):
Option
Information
-d
Displays information about a directory instead of listing its contents.
-g
Like -l option, but do not list owner.
-h
Displays file sizes in the most appropriate format (byte, kilobyte, megabyte, gigabyte, ...). h stands for Human Readable. Needs to be used with -l option.
-s
Displays the allocated size of each file, in blocks. In the ls command, the default size of a single block is 1024-Byte. In the GNU/Linux operating system, "block" is the smallest unit of storage in the file system, and generally speaking, one block is equal to 4096-Byte. In the Windows operating system, taking the NTFS file system as an example, its smallest storage unit is called a "Cluster". The definition of the minimum storage unit name may vary depending on different file systems.
-A
Displays all files in the directory except . and ..
-R
Displays the contents of subdirectories recursively.
-F
Displays the type of files. Prints a / for a directory, * for executables, @ for a symbolic link, and nothing for a text file.
-X
Sorts files according to their extensions.
Description of columns generated by running the ls -lia command:
Number of subdirectories (. and .. included). For a file, it represents the number of hard links, and 1 represents itself.
rockstar
User ownership.
rockstar
Group ownership.
4096
For files, it shows the size of the file. For directories, it shows the fixed value of 4096 bytes occupied by the file naming. To calculate the total size of a directory, use du -sh rockstar/
25 oct. 08:10
Last modified date.
rockstar
The name of the file (or directory).
Note
Aliases are frequently positioned in common distributions.
This is the case of the alias ll:
alias ll='ls -l --color=auto'
The ls command has many options. Here are some advanced examples of uses:
List the files in /etc in order of last modification:
List /var files larger than 1 megabyte but less than 1 gigabyte. The example here uses advanced grep commands with regular expressions. Novices don't have to struggle too much, there will be a special tutorial to introduce these regular expressions in the future.
The touch command changes the timestamp of a file or creates an empty file if the file does not exist.
touch[-tdate]file
Example:
touch/home/rockstar/myfile
Option
Information
-t date
Changes the date of last modification of the file with the specified date.
Date format: [AAAA]MMJJhhmm[ss]
Tip
The touch command is primarily used to create an empty file, but it can be useful for incremental or differential backups for example. Indeed, the only effect of executing a touch on a file will be to force it to be saved during the next backup.
Delete a directory and recursively delete its subdirectories.
Note
The rm command itself does not ask for confirmation when deleting files. However, with a Red Hat/Rocky distribution, rm does ask for confirmation of deletion because the rm command is an alias of the rm -i command. Don't be surprised if on another distribution, like Debian for example, you don't get a confirmation request.
Deleting a folder with the rm command, whether the folder is empty or not, will require the -r option to be added.
The end of the options is signaled to the shell by a double dash --.
In the example:
$>-hard-hard# To create an empty file called -hard-hard
hard-hard
[CTRL+C]Tointerruptthecreationofthefile
$rm-f---hard-hard
The hard-hard file name starts with a -. Without the use of the -- the shell would have interpreted the -d in -hard-hard as an option.
Using the ENTER key, the move is line by line. Using the SPACE key, the move is page by page. /text allows you to search for the occurrence in the file.
The tac command does almost the opposite of the cat command. It displays the contents of a file starting from the end (which is particularly interesting for reading logs!).
Example: Display a log file by displaying the last line first:
With the -f option, the change information of the file will always be output unless the user exits the monitoring state with CTRL + C. This option is very frequently used to track log files (the logs) in real time.
Without the -n option, the tail command displays the last 10 lines of the file.
It allows you to order the result of a command or the content of a file in a given order, numerically, alphabetically, by size (KB, MB, GB) or in reverse order.
Specify the columns to be separated. You can specify multiple columns.
-n
Requests a numeric sort.
-o file
Saves the sort to the specified file.
-t
Specify a delimiter, which requires that the contents of the corresponding file must be regularly delimited column contents, otherwise they cannot be sorted properly.
-r
Reverse the order of the result. Used in conjunction with the -n option to sort in order from largest to smallest.
-u
Remove duplicates after sorting. Equivalent to sort file | uniq.
The sort command sorts the file only on the screen. The file is not modified by the sorting. To save the sort, use the -o option or an output redirection >.
By default, the numbers are sorted according to their character. Thus, "110" will be before "20", which will itself be before "3". The -n option must be specified so that the numeric character blocks are sorted by their value.
The sort command reverses the order of the results, with the -r option:
In this example, the sort command will sort the contents of the /etc/passwd file this time from largest uid (user identifier) to smallest.
Some advanced examples of using the sort command:
Shuffling values
The sort command also allows you to shuffle values with the -R option:
sort-R/etc/passwd
Sorting IP addresses
A system administrator is quickly confronted with the processing of IP addresses from the logs of his services such as SMTP, VSFTP or Apache. These addresses are typically extracted with the cut command.
It is possible to use the -exec option of the find command to execute a command on each result line:
find/tmp-name*.txt-execrm-f{}\;
The previous command searches for all files in the /tmp directory named *.txt and deletes them.
Understand the -exec option
In the example above, the find command will construct a string representing the command to be executed.
If the find command finds three files named log1.txt, log2.txt, and log3.txt, then the find command will construct the string by replacing in the string rm -f {} \; the braces with one of the results of the search, and do this as many times as there are results.
The ; character is a special shell character that must be protected by a \ to prevent it from being interpreted too early by the find command (and not in the -exec).
Tip
$ find /tmp -name *.txt -delete does the same thing.
On UNIX and Linux systems, there are three standard streams. They allow programs, via the stdio.h library, to input or output information.
These streams are called X channel or X file descriptor.
By default:
the keyboard is the input device for channel 0, called stdin ;
the screen is the output device for channels 1 and 2, called stdout and stderr.
stderr receives the error streams returned by a command. The other streams are directed to stdout.
These streams point to peripheral files, but since everything is a file in UNIX/Linux, I/O streams can easily be diverted to other files. This principle is the strength of the shell.
It is possible to redirect the input stream from another file with the character < or <<. The command will read the file instead of the keyboard:
ftp-inserverftp<<ftp-commands.txt
Note
Only commands that require keyboard input will be able to handle input redirection.
Input redirection can also be used to simulate user interactivity. The command will read the input stream until it encounters the defined keyword after the input redirection.
This feature is used to script interactive commands:
$ftp-inserverftp<< ENDuser alice passwordput filebyeEND
The keyword END can be replaced by any word.
$ftp-inserverftp<< STOPuser alice passwordput filebyeSTOP
The shell exits the ftp command when it receives a line containing only the keyword.
Warning
The ending keyword, here END or STOP, must be the only word on the line and must be at the beginning of the line.
The standard input redirection is rarely used because most commands accept a filename as an argument.
The command wc could be used like this:
$wc-l.bash_profile
27.bash_profile# the number of lines is followed by the file name
$wc-l<.bash_profile
27# returns only the number of lines
Standard output can be redirected to other files using the > or >> characters.
The simple > redirection overwrites the contents of the output file:
date+%F>date_file
When the >> character is used, it indicates that the output result of the command is appended to the file content.
date+%F>>date_file
In both cases, the file is automatically created when it does not exist.
The standard error output can also be redirected to another file. This time it will be necessary to specify the channel number (which can be omitted for channels 0 and 1):
Redirection of stderr to a "bottomless pit" (/dev/null):
ls-R/2>>/dev/null
When both output streams are redirected, no information is displayed on the screen. To use both the output redirection and to keep the display, you will have to use the command tee.
A pipe is a mechanism allowing you to link the standard output of a first command to the standard input of a second command.
This communication is uni directional and is done with the | symbol. The pipe symbol | is obtained by pressing the SHIFT + | simultaneously.
All data sent by the control on the left of the pipe through the standard output channel is sent to the standard input channel of the control on the right.
The commands particularly used after a pipe are filters.
Colorize the result of the grep command: alias grep='grep --color=auto'
mcd function
It is common to create a folder and then move around in it: mcd() { mkdir -p "$1"; cd "$1"; }
cls function
Move to a folder and list its contents: cls() { cd "$1"; ls; }
backup function
Create a backup copy of a file: backup() { cp "$1"{,.bak}; }
extract function
Extract any type of archive:
extract(){if[-f$1];thencase$1in*.tar.bz2)tarxjf$1;;*.tar.gz)tarxzf$1;;*.bz2)bunzip2$1;;*.rar)unrare$1;;*.gz)gunzip$1;;*.tar)tarxf$1;;*.tbz2)tarxjf$1;;*.tgz)tarxzf$1;;*.zip)unzip$1;;*.Z)uncompress$1;;*.7z)7zx$1;;*)echo"'$1' cannot be extracted via extract()";;esacelseecho"'$1' is not a valid file"fi}
If alias cmount returns the following: alias cmount="mount | column -t"
Then we can use cmount to show all of the system mounts in columns like this: [root]# cmount
which would return our mounted filesystem in the following format: