what is the standard option to provide a command line program to view its documentation

Commands for Linux Users¶

In this chapter you will learn how to piece of work with Linux with the commands.


Objectives : In this chapter, hereafter Linux administrators will learn how to:

✔ movement in the system tree;
✔ create a text file, display its contents and change it;
✔ use the most useful Linux commands.

šŸ user commands, linux

Knowledge: ⭐
Complexity: ⭐

Reading time: 40 minutes


Generalities¶

Electric current Linux systems accept graphical utilities defended to the work of an administrator. All the same, it is of import to be able to use the interface in command line fashion for several reasons:

  • The bulk of system commands are mutual to all Linux distributions, which is non the case for graphical tools.
  • It can happen that the system does non start correctly but that a backup command interpreter remains accessible.
  • Remote assistants is done on the command line with an SSH terminal.
  • In lodge to preserve server resource, 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 last, to manage its resources, its files, to identify the station, the terminal, and the connected users, etc.

The users¶

The user of a Linux system is defined in the /etc/passwd file, by:

  • a login proper noun, more ordinarily called "login", containing no spaces;
  • a numeric identifier : UID (User Identifier);
  • a group identifier : GID (Grouping Identifier);
  • a command interpreter, a shell, which tin can be different from one user to some other;
  • a connection directory, the home directory.

In other files by:

  • a password, which will exist encrypted before being stored (/etc/shadow);
  • a command prompt, or prompt login, which will exist symbolized by a # for administrators and a $ for other users (/etc/profile).

Depending on the security policy implemented on the system, the password volition have to contain a certain number of characters and meet certain complexity requirements.

Among the existing control interpreters, the Bourne-Again Shell (/bin/bash) is the one most frequently used. It is assigned by default to new users. For diverse reasons, avant-garde Linux users tin can choose culling shells from among the Korn Trounce (ksh), the C Shell (csh), etc.

The user'due south login directory is by convention stored in the /home directory of the workstation. It volition 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 existence multi-user, it is possible to connect several users several times, on dissimilar physical terminals (TTY) or virtual terminals (PTS). Virtual terminals are bachelor within a graphical environs. A user switches from one physical last to another using Alt + Fx from the command line or using CTRL + Alt + Fx.

The beat¶

Once the user is connected to a console, the beat out displays the command prompt. Information technology and so behaves like an infinite loop, with each argument entered:

  • displaying the command prompt;
  • reading the control ;
  • syntax analysis ;
  • substitution of special characters ;
  • execute the command;
  • display the command prompt;
  • etc.

The key sequence CTRL + C is used to interrupt a running command.

The utilise of a command generally follows this sequence:

                                            command                [option(s)]                [arguments(s)]                          

The proper noun of the control is often in lower case.

A infinite separates each item.

Short options begin with a dash (-l), while long options brainstorm with two dashes (--list). A double dash (--) indicates the end of the selection list.

It is possible to group some short options together:

is equivalent to:

In that location can of class be several arguments after an selection:

                            $ ls -lia /etc /dwelling /var                          

In the literature, the term "pick" is equivalent to the term "parameter," which is more commonly used in programming. The optional side of an selection or statement 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|eastward|i].

Full general commands¶

concerning, whatis and man commands¶

It is impossible for an ambassador at whatever level to know all the commands and options in particular. A manual is usually available for all installed commands.

apropos command¶

The control apropos allows you to search by keyword within these manual pages:

Options Observations
-s, --sections list or --section listing Express to transmission sections.
-a or --and Displays merely the item matching all the provided keywords.

Case:

                            $ apropos clear clear                (                1                )                - clear the final screen clear_console                (                ane                )                - clear the console clearenv                (                3                )                - clear the environs clearerr                (                three                )                - check and reset stream status clearerr_unlocked                (                3                )                - nonlocking stdio functions feclearexcept                (                three                )                - floating-point rounding and exception handling fwup_clear_status                (                3                )                - library to back up direction of system firmware updates klogctl                (                three                )                -                read                and/or clear kernel message band buffer;                fix                console_loglevel sgt-samegame                (                6                )                - Block-immigration puzzle syslog                (                2                )                -                read                and/or clear kernel message band buffer;                set                console_loglevel timerclear                (                3                )                - timeval operations XClearArea                (                3                )                - clear area or window XClearWindow                (                3                )                - articulate area or window XSelectionClearEvent                (                3                )                - SelectionClear issue structure                          

To notice the command that will let irresolute the password of an account:

                            $ concerning --exact password  -a modify chage                (                1                )                - change user password expiry information passwd                (                1                )                - change user countersign                          

whatis command¶

The whatis control displays the clarification of the command passed as statement:

Example:

                            $ whatis clear clear                (                one                )                - articulate the last screen                          

homo command¶

In one case establish by apropos or whatis, the manual is read by human being ("Human is your friend"). This set of manuals is divided into 8 sections, grouping information by topic, the default section being ane:

  1. Executable programs or commands;
  2. Organisation calls (functions given by the kernel);
  3. Library calls (functions given by the library);
  4. Special files (usually found in /dev);
  5. File Formats and conventions (configuration files such equally etc/passwd);
  6. Games (such as character-based applications);
  7. Miscellaneous (e.g. man (seven));
  8. System administration commands (unremarkably only for root);
  9. Kernel routines (non-standard).

Information nearly each section tin be accessed by typing man 10 intro, where x is the section number.

The command:

will tell the ambassador about the passwd control, its options, etc. While a:

volition inform him about the files related to the command.

Not all manual pages are translated from English. However, English manual pages are usually very authentic and provide all the data you need. The grammar and separation rules it uses may confuse beginner administrators, but after practice, I'm sure you'll find the information yous want.

The navigation in the manual is done with the arrows and . The manual is exited by pressing the q key.

shutdown command¶

The shutdown control allows you to electrically close down a Linux server, either immediately or after a certain period of time.

                            shutdown                [-h]                [-r]                time                [bulletin]                          

The shutdown time should be specified in the format hh:mm for a precise time, or +mm for a filibuster in minutes.

To force an immediate stop, the give-and-take at present will supersede the fourth dimension. In this case, the optional bulletin is not sent to other users of the system.

Examples:

                                            [root]                # shutdown -h 0:thirty "Server shutdown at 0:30"                [root]                # shutdown -r +5                          

Options:

Options Remarks
-h Shutdown the system electrically
-r Restarts the system

history control¶

The history command displays the history of commands that take been entered by the user.

The commands are stored in the .bash_history file in the user'south login directory.

Example of a history command

                            $                history                147                man ls                148                man                history                          
Options Comments
-w Write the current history to the history file
-c The -c option will delete the history of the current session (but not the contents of the .bash_history file).
  • Manipulating history:

To manipulate the history, the following commands entered from the command prompt volition:

Keys Function
!! Call back the final control placed.
!n Recall the command by its number in the listing.
!string Recollect the nigh recent command beginning with the string.
Recall the virtually recent command starting time with the string.
Recall the most recent command beginning with the string.

The machine-completion¶

Auto-completion is also a great help.

  • Information technology allows y'all to complete commands, entered paths, or file names.
  • A press of the TAB primal completes the entry in the case of a single solution.
  • Otherwise, a second press will be required to obtain the listing of possibilities.

If a double press of the TAB key causes no reaction from the arrangement, then at that place is no solution to the electric current completion.

Brandish and identification¶

articulate command¶

The clear command clears the contents of the terminal screen. In fact, to exist more precise, it shifts the brandish then that the command prompt is at the summit of the screen on the beginning line.

In a last, the brandish volition be permanently subconscious, whereas in a graphical interface, a scrollbar will allow you to go dorsum in the history of the virtual final.

Tip

CTRL + L will accept the same result as the clear command

echo control¶

The repeat command is used to display a string of characters.

This command is most commonly used in administration scripts to inform the user during execution.

The -north option indicates no newline output string (by default, newline output string).

                            beat >                echo                -northward                "123"                ;                echo                "456"                123456                shell >                echo                "123"                ;                echo                "456"                123                456                          

For various reasons, the script programmer may need to use special sequences (starting with a \ graphic symbol). In this case, the -e option will be stipulated, assuasive interpretation of the sequences.

Among the frequently used sequences, we tin mention:

Sequence Event
\a Send a sonor bip
\b Back
\n Adds a line break
\t Adds a horizontal tab
\v Adds vertical tab

date command¶

The date command displays the appointment and fourth dimension. The command has the following syntax:

                            date                [-d AAAAMMJJ]                [format]                          

Examples:

                            $ appointment Mon May                24                sixteen:46:53 CEST                2021                $ date -d                20210517                +%j                137                          

In this final case, the -d option displays a given date. The +%j option formats this date to show merely the day of the year.

Warning

The format of a appointment can change depending on the value of the language divers in the environs variable $LANG.

The date display can follow the post-obit formats:

Pick Format
+%A Locale's full weekday proper name (east.m., Sun)
+%B Locale's full month name (due east.g., Jan)
+%c Locale'due south date and time (eastward.g., Thu Mar 3 23:05:25 2005)
+%d Twenty-four hours of month (e.g., 01)
+%F Appointment in YYYY-MM-DD format
+%G Year
+%H Hour (00..23)
+%j Twenty-four hour period of the yr (001..366)
+%m Month number (01..12)
+%M Minute (00..59)
+%R Fourth dimension in hh:mm format
+%s Seconds since January 1, 1970
+%S Second (00..60)
+%T Time in hh:mm:ss format
+%u Day of the week (1 for Monday)
+%V Week number (+%V)
+%10 Date in format DD/MM/YYYY

The date command also allows you lot to change the system date and time. In this instance, the -southward selection volition be used.

                                            [root]                # date -s "2021-05-24 10:nineteen"                          

The format to be used following the -s choice is this:

                            date -s                "[AA]AA-MM-JJ hh:mm:[ss]"                          

id, who and whoami commands¶

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。

                            $ id rockstar                uid                =                1000                (rockstar)                gid                =                1000                (rockstar)                groups                =                1000                (rockstar),10(wheel)                          

The -thousand, -G, -n and -u options display the main group GID, subgroup GIDs, names instead of numeric identifiers, and the user's UID respectively.

The whoami command displays the login of the current user.

The who command alone displays the names of logged in users:

                            $ who rockstar tty1                2021-05-24                x:30 root     pts/0                2021-05-24                10:31                          

Since Linux is multi-user, it is likely that multiple sessions are open on the aforementioned 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 letters.

  • tty: represents a terminal.
  • pts/: represents a virtual console in a graphical surroundings with the number after representing the example of the virtual console (0, 1, two...)

The -r option also displays the runlevel (meet chapter "startup").

File tree¶

In Linux, the file tree is an inverted tree, chosen 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 /dwelling house directory.

When the user logs in, the electric current directory is the login directory.

An absolute path references a file from the root by traversing the entire tree to the file level:

  • /domicile/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, volition 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 offset ./ in the tree volition only really be required to run an executable file.

Errors in paths can crusade many bug: creating folders or files in the wrong places, unintentional deletions, etc. It is therefore strongly recommended to apply auto-completion when inbound paths.

our example tree

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 electric current directory does not affair. We start at the root, and work our way downwardly to the directories abode, groupA, alice and finally the file myfile: /home/groupA/alice/myfile.
  • By a relative path, our starting betoken being the current directory bob, we become up 1 level through .. (i.e., into the groupA directory), then down into the alice directory, and finally the myfile file: ../alice/myfile.

pwd command¶

The pwd (Impress Working Directory) command displays the absolute path of the electric current directory.

Utilise a relative path to reference a file or directory, or use the cd command to move to another directory, Y'all must know its location in the file tree.

Depending on the type of beat and the dissimilar 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.

cd command¶

The cd (Change Directory) control allows you to change the current directory, in other words, to move through the tree.

                            $                cd                /tmp $                pwd                /tmp $                cd                ../ $                pwd                / $                cd                $                pwd                /home/rockstar                          

As you tin can encounter in the final case to a higher place, the command cd with no arguments moves the current directory to the home directory.

ls control¶

The ls command displays the contents of a directory.

                            ls                [-a]                [-i]                [-l]                [directory1]                [directory2]                []                          

Example:

The primary options of the ls command are:

Choice Information
-a Displays all files, even subconscious ones. Hidden files in Linux are those outset with ..
-i Displays inode numbers.
-l The -l command displays a vertical listing of files with boosted information formatted in columns.

The ls command, however, has a lot of options (see homo):

Selection Information
-d Displays data about a directory instead of listing its contents.
-g Displays UID and GID rather than owner names.
-h Displays file sizes in the most appropriate format (byte, kilobyte, megabyte, gigabyte, ...). h stands for Human Readable.
-s Displays the number of blocks occupied by the file. One block equals 400K.
-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 goose egg for a text file.
-X Sort files according to their extensions.
  • Clarification of columns:
                            $ ls -lia /home                78489                drwx------                4                rockstar rockstar                4096                25                october.                08:x rockstar                          
Value Data
78489 Inode Number.
drwx------ File type (d) and rights (rwx------).
iv Number of subdirectories (. and .. included). For a file, information technology represents the number of hard links, and 1 represents itself.
rockstar User ownership.
rockstar Group buying.
4096 For files, information technology shows the size of the file. For directories, it shows the fixed value of 4096 bytes occupied past the file naming. To calculate the full size of a directory, use du -sh rockstar/
25 october. 08:10 Terminal modified date.
rockstar The proper noun of the file (or directory).

Note

Aliases are oftentimes positioned in common distributions.

This is the case of the allonym ll:

                                alias ll='ls -l --color=auto'                              

The ls command has many options and here are some avant-garde examples of uses:

  • Listing the files in /etc in club of last modification:
                            $ ls -ltr /etc total                1332                -rw-r--r--.                1                root root                662                29                may                2021                logrotate.conf -rw-r--r--.                1                root root                272                17                may.                2021                mailcap -rw-------.                1                root root                122                12                may.                2021                securetty ... -rw-r--r--.                2                root root                85                18                may.                17:04 resolv.conf -rw-r--r--.                1                root root                44                18                may.                17:04 adjtime -rw-r--r--.                i                root root                283                18                may.                17:05 mtab                          
  • List /var files larger than 1 megabyte but less than i gigabyte:
                            $ ls -lhR  /var                |                grep                \-                |                grep                [                1-9]*M ... -rw-r--r--.                1                apache apache                1.2M                10                may.                13:02 XB RiyazBdIt.ttf -rw-r--r--.                ane                apache apache                1.2M                x                may.                thirteen:02 XB RiyazBd.ttf -rw-r--r--.                i                apache apache                1.1M                10                may.                13:02 XB RiyazIt.ttf ...                          

Of course, we highly recommend that you use the find command.

                            $ find /var -size +1M -a -size -1024M  -a -type f  -exec ls -lh                {}                \;                          
  • Show the rights on a folder:

To find out the rights to a folder, in our instance /etc, the following command would non be appropriate:

                            $ ls -fifty /etc total                1332                -rw-r--r--.                ane                root root                44                eighteen                november.                17:04 adjtime -rw-r--r--.                1                root root                1512                12                janv.                2010                aliases -rw-r--r--.                one                root root                12288                17                november.                17:41 aliases.db drwxr-xr-ten.                2                root root                4096                17                november.                17:48 alternatives ...                          

The higher up control volition display the contents of the folder (inside) past default. For the folder itself, you can use the -d option.

                            $ ls -ld /etc drwxr-xr-x.                69                root root                4096                18                nov.                17:05 /etc                          
  • Sort past file size, largest commencement:
  • fourth dimension/date format with -l:
                            $ ls -l --time-fashion=                "+%Y-%thou-%d %k-%d %H:%G"                / full                12378                dr-xr-xr-ten.                2                root root                4096                2014-eleven-23                11-23                03:13 bin dr-xr-xr-x.                v                root root                1024                2014-11-23                eleven-23                05:29 kicking                          
  • Add together the trailing slash to the end of folders:

By default, the ls command does not display the terminal slash of a binder. In some cases, similar for scripts for example, it is useful to display them:

  • Hide some extensions:

mkdir command¶

The mkdir command creates a directory or directory tree.

                            mkdir                [-p]                directory                [directory]                [...]                          

Example:

                            $ mkdir /domicile/rockstar/work                          

The "rockstar" directory must be to create the "work" directory.

Otherwise, the -p option should exist used. The -p selection creates the parent directories if they practise not exist.

Danger

Information technology is not recommended to use Linux control names equally directory or file names.

impact command¶

The touch control changes the timestamp of a file or creates an empty file if the file does not be.

Instance:

                            $ impact /abode/rockstar/myfile                          
Option Information
-t date Changes the date of concluding modification of the file with the specified date.

Date format: [AAAA]MMJJhhmm[ss]

Tip

The touch on control 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 side by side backup.

rmdir command¶

The rmdir control deletes an empty directory.

Example:

                            $ rmdir /home/rockstar/work                          
Option Data
-p Removes the parent directory or directories provided if they are empty.

Tip

To delete both a non-empty directory and its contents, use the rm control.

rm command¶

The rm command deletes a file or directory.

                            rm                [-f]                [-r]                file                [file]                [...]                          

Danger

Whatsoever deletion of a file or directory is final.

Options Information
-f Do not ask for confirmation of deletion.
-i Requires confirmation of deletion.
-r Recursively deletes subdirectories.

Notation

The rm command itself does not ask for confirmation when deleting files. However, with a RedHat/Rocky distribution, rm does ask for confirmation of deletion because the rm command is an allonym 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 binder with the rm command, whether the binder is empty or not, will require the -r option to exist added.

The end of the options is signaled to the shell past a double dash --.

In the example:

                            $ >-hard-hard                # To create an empty file called -hard-hard                difficult-hard                [CTRL+C]                To interrupt the cosmos of the file $ rm -f -- -hard-difficult                          

The hard-hard file name starts with a -. Without the employ of the -- the shell would have interpreted the -d in -difficult-hard as an pick.

mv command¶

The mv control moves and renames a file.

                            mv file                [file ...]                destination                          

Examples:

                            $ mv /home/rockstar/file1 /dwelling/rockstar/file2 $ mv /home/rockstar/file1 /habitation/rockstar/file2 /tmp                          
Options Information
-f Don't ask for confirmation if overwriting the destination file.
-i Asking confirmation if overwriting destination file (default).

A few concrete cases will help you empathize the difficulties that can arise:

                            $ mv /home/rockstar/file1 /home/rockstar/file2                          

Renames file1 to file2, if file2 already exists, it will be replaced by file1.

                            $ mv /home/rockstar/file1 /domicile/rockstar/file2 /tmp                          

Moves file1 and file2 into the /tmp directory.

                            $ mv file1 /repexist/file2                          

Moves file1 into repexist and renames it file2.

file1 is renamed to file2.

If the destination directory exists, file1 is moved to /repexist.

If the destination directory does not exist, file1 is renamed to wrongrep in the root directory.

cp command¶

The cp command copies a file.

                            cp file                [file ...]                destination                          

Example:

                            $ cp -r /abode/rockstar /tmp                          
Options Information
-i Asking confirmation if overwriting (default).
-f Practice not ask for confirmation if overwriting the destination file.
-p Keeps the owner, permissions and timestamp of the copied file.
-r Copies a directory with its files and subdirectories.
-south Creates a symbolik links rather than copying.

file1 is copied to /repexist under the name file2.

file1 is copied as file2 to this directory.

If the destination directory exists, file1 is copied to /repexist.

If the destination directory does not exist, file1 is copied under the name wrongrep to the root directory.

Visualization¶

file control¶

The file command displays the type of a file.

Example:

                            $ file /etc/passwd /etc /etc/passwd:    ASCII text /etc:        directory                          

more control¶

The more than control displays the contents of one or more than files screen past screen.

Example:

                            $ more /etc/passwd root:ten:0:0:root:/root:/bin/bash ...                          

Using the ENTER key, the move is line by line. Using the SPACE key, the move is page by folio. /text allows yous to search for the occurrence in the file.

less command¶

The less command displays the contents of one or more files. The less command is interactive and has its own commands for use.

The commands specific to less are:

Command Action
h Assistance.
Arrows Move upwardly, down a line, or to the right or left.
Enter Move down one line.
Space Move downwards one page.
PgUp and PgDn Movement upwards or down ane page.
Brainstorm and End Move to the beginning or finish of a file.
/text Search for text.
q Quit the less command.

cat control¶

The cat command concatenates the contents of multiple files and displays the issue on the standard output.

Example one - Displaying the contents of a file to the standard output:

Example 2 - Displaying the contents of multiple files to standard output:

                            $ cat /etc/passwd /etc/grouping                          

Example 3 - Displaying the contents of several files in the file usersAndGroups.txt:

                            $ cat /etc/passwd /etc/group > usersAndGroups.txt                          

Example 4 - Displaying the line numbering:

                            $ cat -n /etc/profile                1                # /etc/contour: system-broad .profile file for the Bourne shell (sh(1))                ii                # and Bourne compatible shells (bash(i), ksh(1), ash(i), ...).                3                4                if                [                "`id -u`"                -eq                0                ]                ;                then                5                PATH                =                "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"                six                else            

Example five - Shows the numbering of not-empty lines:

                            $ cat -b /etc/profile                1                # /etc/contour: arrangement-wide .profile file for the Bourne shell (sh(1))                2                # and Bourne compatible shells (fustigate(i), ksh(one), ash(1), ...).                3                if                [                "`id -u`"                -eq                0                ]                ;                then                4                PATH                =                "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"                v                else            

tac command¶

The tac command does nearly the contrary of the cat control. Information technology displays the contents of a file starting from the end (which is particularly interesting for reading logs!).

Example: Brandish a log file by displaying the last line first:

                                            [root]                # tac /var/log/messages | less                          

head command¶

The head command displays the offset of a file.

Option Ascertainment
-due north x Display the start x lines of the file

By default (without the -n option), the head command volition display the first 10 lines of the file.

tail command¶

The tail control displays the end of a file.

Option Observation
-due north 10 Displays the concluding ten lines of the file
-f Displays changes to the file in existent time

Example:

                            tail -north                iii                /etc/passwd sshd:x:74:74:Privilege-separeted sshd:/var/empty /sshd:/sbin/nologin tcpdump::x:72:72::/:/sbin/nologin user1:ten:500:500:grp1:/home/user1:/bin/fustigate                          

With the -f option, the tail command does not give back and runs until the user interrupts information technology with the sequence CTRL + C. This option is very ofttimes used to track log files (the logs) in existent time.

Without the -n selection, the tail command displays the terminal ten lines of the file.

sort command¶

The sort control sorts the lines of a file.

It allows yous to guild the issue of a control or the content of a file in a given gild, numerically, alphabetically, past size (KB, MB, GB) or in contrary social club.

                            sort                [-kx]                [-northward]                [-u]                [-o file]                [-ty]                file                          

Example:

                            $ sort -k3 -t: -n /etc/passwd root:x:0:0:root:/root:/bin/bash adm:x:three:iv:adm:/var/adm/:/sbin/nologin                          
Pick Ascertainment
-kx Specifies the x column to sort on
-n Requests a numeric sort
-o file Saves the sort to the specified file
-ty Specifies the field separator graphic symbol y
-r Reverse the lodge of the result
- u But keeps unique results

The sort control 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 >.

Past default, the numbers are sorted according to their character. Thus, "110" volition be earlier "xx", which will itself be before "3". The -due north option must exist specified so that the numeric graphic symbol blocks are sorted by their value.

The sort command reverses the order of the results, with the -r option:

                            $ sort -k3 -t: -n -r /etc/passwd root:x:0:0:root:/root:/bin/bash adm:x:3:four:adm:/var/adm/:/sbin/nologin                          

In this case, the sort command volition sort the contents of the /etc/passwd file this time from largest uid to smallest.

Some advanced examples of using the sort command:

  • Shuffling values

The sort command also allows you to shuffle values with the -R pick:

  • Sorting IP addresses

A system administrator is quickly confronted with the processing of IP addresses from the logs of his services such equally SMTP, VSFTP or Apache. These addresses are typically extracted with the cut command.

Here is an example with the file dns-client.txt:

                            192.168.1.10 192.168.1.200 5.1.150.146 208.128.150.98 208.128.150.99                          
                            $ sort -nr dns-client.txt                208.128.150.99                208.128.150.98                192.168.one.200                192.168.1.x                5.1.150.146                          
  • Sorting file by removing duplicates

The sort command knows how to remove the duplicates from the file output using -u every bit option.

Hither is an example with the file colours.txt:

                            $ sort -u colours.txt Blue Green Pink Blood-red                          
  • Sorting file by sizes

The sort control knows how to recognize file sizes, from commands like ls with the -h pick.

Here is an example with the file size.txt:

                            1,7G 18M 69K two,4M i,2M four,2G 6M 124M 12,4M 4G                          
                            $ sort -hour size.txt                4,2G 4G                1,7G 124M 18M                12,4M 6M                two,4M                1,2M 69K                          

wc command¶

The wc command counts the number of lines, words and/or bytes in a file.

                            wc                [-l]                [-g]                [-w]                file                [files]                          
Option Observation
-c Count the number of bytes.
-grand Count the number of characters.
-l Counts the number of lines.
-w Counts the number of words.

find command¶

The discover control searches for files or directories location.

                            find directory                [-name name]                [-blazon blazon]                [-user login]                [-date appointment]                          

Since at that place are and so many options to the find command, information technology is best to refer to the man.

If the search directory is not specified, the find control volition search from the electric current directory.

Option Ascertainment
-perm permissions Search for files by their permissions.
-size size Search for files past size.

-exec option of the find command¶

It is possible to use the -exec choice of the find command to execute a command on each result line:

                            $ discover /tmp -proper name *.txt -exec rm -f                {}                \;                          

The previous command searches for all files in the /tmp directory named *.txt and deletes them.

Understand the -exec choice

In the example above, the discover command will construct a string representing the command to exist executed.

If the find command finds three files named log1.txt, log2.txt, and log3.txt, then the find command volition construct the string by replacing in the string rm -f {} \; the braces with ane of the results of the search, and practise this as many times as there are results.

This will requite us:

                                rm -f /tmp/log1.txt ; rm -f /tmp/log2.txt ; rm -f /tmp/log3.txt ;                              

The ; grapheme is a special beat out character that must be protected by a \ to prevent information technology from being interpreted too early by the find command (and not in the -exec).

Tip

$ find /tmp -name *.txt -delete does the same thing.

whereis command¶

The whereis command searches for files related to a command.

                            whereis                [-b]                [-thou]                [-s]                command                          

Example:

                            $ whereis -b ls ls: /bin/ls                          
Option Ascertainment
-b Search only the binary file.
-k Searches just for man pages.
-s Searches only for source files.

grep control¶

The grep control searches for a cord in a file.

                            grep                [-w]                [-i]                [-five]                "string"                file                          

Case:

                            $ grep -w                "root:"                /etc/passwd root:x:0:0:root:/root:/bin/bash                          
Option Observation
-i Ignore the case of the searched string.
-five Excludes lines containing the string.
-w Search for the exact word.

The grep command returns the consummate line containing the cord you are looking for. * The ^ special character is used to search for a string at the beginning of a line. * The special grapheme $ searches for a string at the end of a line.

                            $ grep -w                "^root"                /etc/passwd                          

Notation

This command is very powerful and information technology is highly recommended to consult its manual. It has many derivatives.

It is possible to search for a string in a file tree with the -R option.

                            grep -R                "Virtual"                /etc/httpd                          

Meta-characters (wildcards)¶

Meta-characters replace ane or more characters (or even an absenteeism of characters) during a search. These meta-characters are also known every bit wildcards.

They tin be combined.

The * grapheme replaces a string composed of any characters. The * graphic symbol can also represent an absence of character.

                            $ find /home -proper noun                "exam*"                /home/rockstar/test /dwelling house/rockstar/test1 /dwelling house/rockstar/test11 /home/rockstar/tests /home/rockstar/test362                          

Meta-characters allow more complex searches by replacing all or office of a discussion. Just replace the unknowns with these special characters.

The character ? replaces a unmarried grapheme, whatever it is.

                            $ detect /dwelling -proper noun                "test?"                /abode/rockstar/test1 /abode/rockstar/tests                          

The square brackets [ and ] are used to specify the values that a unmarried character can take.

                            $ discover /home -proper name                "test[123]*"                /abode/rockstar/test1 /dwelling house/rockstar/test11 /home/rockstar/test362                          

Note

Always surround words containing meta-characters with " to prevent them from being replaced past the names of files that meet the criteria.

Warning

Do not confuse vanquish meta-characters with regular expression meta-characters. The grep command uses regular expression meta-characters.

Redirects and pipes¶

Standard input and output¶

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 chosen 10 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 two, called stdout and stderr.

standards channels

stderr receives the error streams returned by a control. The other streams are directed to stdout.

These streams bespeak to peripheral files, merely since everything is a file in UNIX/Linux, I/O streams can hands exist diverted to other files. This principle is the strength of the trounce.

Input redirection¶

It is possible to redirect the input stream from another file with the graphic symbol < or <<. The control will read the file instead of the keyboard:

                            $ ftp -in serverftp << ftp-commands.txt                          

Note

Only commands that require keyboard input will be able to handle input redirection.

Input redirection can besides be used to simulate user interactivity. The control will read the input stream until information technology encounters the defined keyword afterwards the input redirection.

This feature is used to script interactive commands:

                            $ ftp -in serverftp                << END                user alice countersign                put file                bye                END                          

The keyword Finish can be replaced by any word.

                            $ ftp -in serverftp                << End                user alice password                put file                bye                STOP                          

The shell exits the ftp command when it receives a line containing only the keyword.

Alert

The ending keyword, here Terminate or STOP, must be the simply word on the line and must be at the beginning of the line.

The standard input redirection is rarely used considering about commands have a filename every bit an argument.

The command wc could exist 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                          

Output redirection¶

Standard output can exist redirected to other files using the > or >> characters.

The simple > redirection overwrites the contents of the output file:

while the double redirection >> adds (concatenates) to the content of the output file.

In both cases, the file is automatically created when it does non exist.

The standard error output can also be redirected to some other file. This fourth dimension information technology will be necessary to specify the aqueduct number (which can be omitted for channels 0 and ane):

                            $ ls -R /                ii> errors_file $ ls -R /                2>> errors_file                          

Examples of redirection¶

Redirection of 2 outputs to two files:

                            $ ls -R / >> ok_file                ii>> nok_file                          

Redirection of the ii outputs to a single file:

                            $ ls -R / >> log_file                2>&                1                          

Redirection of stderr to a "abysmal pit" (/dev/cypher):

When both output streams are redirected, no information is displayed on the screen. To apply both the output redirection and to keep the display, you will have to use the control tee.

Pipes¶

A pipe is a machinery assuasive you lot to link the standard output of a first command to the standard input of a 2d command.

This communication is uni directional and is done with the | symbol. The pipe symbol | is obtained past pressing the SHIFT + | simultaneously.

pipe

All data sent by the command 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 later a pipe are filters.

  • Examples:

Display only the first:

Display only the terminate:

Sort the result:

Count the number of words / characters:

Search for a string in the upshot:

                            $ ls -lia /                |                grep fichier                          

Special points¶

tee command¶

The tee command is used to redirect the standard output of a command to a file while maintaining the screen brandish.

It is combined with the | pipe to receive as input the output of the command to be redirected:

                            $ ls -lia /                |                tee fic $ cat fic                          

The -a option adds to the file instead of overwriting information technology.

alias and unalias commands¶

Using alias is a fashion to ask the shell to remember a item control with its options and give it a name.

For case:

volition supplant the command:

The alias command lists the aliases for the current session. Aliases are set by default on Linux distributions. Hither, the aliases for a Rocky server:

                            $                allonym                alias                l.=                'ls -d .* --color=car'                allonym                ll                =                'ls -l --color=auto'                alias                ls                =                'ls --color=motorcar'                allonym                vi                =                'vim'                alias                which                =                'allonym | /usr/bin/which --tty-simply --read-alias --testify-dot --show-tilde'                          

The aliases are only defined temporarily, for the time of the user session.

For permanent use, they must be created in the:

  • .bashrc file in the user's login directory;
  • /etc/profile.d/alias.sh file for all users.

Warning

Special intendance must exist taken when using aliases which can be potentially dangerous! For example, an alias set without the administrator'southward cognition:

The unalias control allows you to delete aliases.

To delete a single allonym:

To delete all aliases:

To disable an alias temporarily, the combination is \<alias proper noun>.

For instance if we do:

it might return the following:

                            ls is an                allonym                to « ls -rt »                          

At present that this is known, we can see the results of using the alias or disabling it i time with the \ by executing the following:

                            $ ls file*                # order by time                file3.txt  file2.txt  file1.txt $                \ldue south file*                # order past name                file1.txt  file2.txt  file3.txt                          

Aliases and useful functions¶

  • grep alias.

Colorize the result of the grep command: alias grep='grep --color=machine'

  • mcd part

It is common to create a folder and then move around in it: mcd() { mkdir -p "$1"; cd "$1"; }

  • cls function

Motility to a binder and list its contents: cls() { cd "$1"; ls; }

  • backup function

Create a fill-in copy of a file: fill-in() { cp "$1"{,.bak}; }

  • extract function

Excerpt whatever type of annal:

                            extract                ()                {                if                [                -f                $1                ]                ;                then                case                $1                in                *.tar.bz2)                tar xjf                $one                ;;                *.tar.gz)                tar xzf                $1                ;;                *.bz2)                bunzip2                $i                ;;                *.rar)                unrar due east                $ane                ;;                *.gz)                gunzip                $1                ;;                *.tar)                tar xf                $1                ;;                *.tbz2)                tar xjf                $1                ;;                *.tgz)                tar xzf                $one                ;;                *.zip)                unzip                $1                ;;                *.Z)                uncompress                $i                ;;                *.7z)                7z x                $one                ;;                *)                echo                "'                $ane                ' cannot be extracted via extract()"                ;;                esac                else                repeat                "'                $1                ' is not a valid file"                fi                }                          
  • If allonym cmount returns the following: alias cmount="mountain | column -t"

Then we can use cmount to evidence all of the system mounts in columns like this: [root]# cmount

which would render our mounted filesystem in the following format:

                            /dev/simfs  on  /                type                simfs                (rw,relatime,usrquota,grpquota)                proc        on  /proc                type                proc                (rw,relatime)                sysfs       on  /sys                type                sysfs                (rw,relatime)                none        on  /dev                type                devtmpfs                (rw,relatime,fashion=                755                )                none        on  /dev/pts                blazon                devpts                (rw,relatime,mode=                600,ptmxmode=                000                )                none        on  /dev/shm                type                tmpfs                (rw,relatime)                none        on  /proc/sys/fs/binfmt_misc                blazon                binfmt_misc                (rw,relatime)                          

The graphic symbol ;

The ; character strings the commands.

The commands will all run sequentially in the order of input once the user presses ENTER.

                            $ ls /;                cd                /abode;                ls -lia;                cd                /                          

Bank check your Knowledge¶

✔ What defines a user under Linux? (vii answers)

✔ What characterizes a long option for a control?

✔ Which commands let you to search for assistance on a command?

  • google
  • chuck --norris
  • info
  • apropos
  • whatis

✔ Which command allows you lot to view a user'southward history?

✔ Which command allows you lot to search for text in a file?

  • find
  • grep

✔ Which command allows you to search for a file?

  • discover
  • grep

✔ Which command redirects the error stream of a command to a new errors.log file?

  • ls -R / 2> errors.log
  • ls -R / 2>> errors.log
  • ls -R / 2> errors.log 2>&1

Concluding update: Apr 8, 2022

Writer: Antoine Le Morvan

Contributors: Steven Spencer, Aditya Putta

escobedotrind1988.blogspot.com

Source: https://docs.rockylinux.org/books/admin_guide/03-commands/

0 Response to "what is the standard option to provide a command line program to view its documentation"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel