Linux command line: dealing with commands

In this chapter, we will further uncover the mystery of commands and even create personal commands.

  • type: Displays the command type.
  • which: Shows the location of the executable file.
  • help: Get help information for Shell built-in commands.
  • man: Display the man page of the command.
  • apropos: Display a list of suitable commands.
  • whatis: displays a brief description of the man page.
  • info: Show the info entry of the command.
  • alias: Create your own command.

5.1 What exactly is a command

Any one of the following four conditions can be called a command.

  • Just like those files we saw in /usr/bin. In this category, a program can be a binary file written and compiled by C and C++, or a script written by a scripting language such as Shell, Perl, Python, Ruby, etc.
  • Built-in commands in the Shell. Bash supports a large number of built-in commands, and the cd command is one of them.
  • Shell function. Shell functions are miniature Shell scripts incorporated into the environment. In the following article, we will introduce the environment configuration and the writing of Shell functions. At present, we only need to know the existence of them.
  • Alias. Aliases are commands that we define ourselves on the basis of other commands.

5.2 Identify commands

Knowing the commands to use is often helpful in certain situations, and the Linux operating system provides several methods.

5.2.1 type-display command type

The type command is a built-in command of the Shell, which can show which type the specified command belongs to. Its usage is as follows:

type_command_

Among them, command is the name of the file you want to check. Here are some examples:

[me@linuxbox ~]$ type type
type is a shell builtin
[me@linuxbox ~]$ type ls
ls is aliased to 'ls --color=tty'
[me@linuxbox ~]$ type cp
cp is /bin/cp

As you can see from the output, there are 3 different commands. Note that ls (taken from the Fedora system) is actually an alias for the ls command with the --color=tty option added. Now we finally know why the output of ls is colored!

5.2.2 Which display shows the location of the file

Sometimes, more than one version of the program is installed in the system. Although this situation is not common on desktop systems, it is common on large servers. In order to determine the exact location of a program, you can use the which command:

[me@linuxbox ~]$ which ls
/bin/ls

The which command only applies to executable files, not to built-in commands or aliases that replace actual executable files. If you try to use the which command with the Shell built-in commands (such as the cd command), there will be no output or an error message:

[me@linuxbox ~]$ which cd
/usr/bin/which: no cd in (/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games)

This is an "exquisite" way of saying "command not found" (command not found).

5.3 Obtaining command documentation

After knowing what a command is, we can now get the documents available for various commands.

5.3.1 help—Get help information for Shell's built-in commands

Bash's own help function can be used for all Shell built-in commands. Just type help and add the name of the built-in command in Shell. Here is an example:

[me@linuxbox ~]$ help cd
cd: cd [-L|[-P [-e]] [-@]] [dir]
    Change the shell working directory.
    Change the current directory to DIR. The default DIR is the value of the
    HOME shell variable.
    The variable CDPATH defines the search path for the directory containing
    DIR. Alternative directory names in CDPATH are separated by a colon (:).
    A null directory name is the same as the current directory. If DIR begins
    with a slash (/), then CDPATH is not used.
    If the directory is not found, and the shell option 'cdable_vars' is set,
    the word is assumed to be a variable name. If that variable has a value,
    its value is used for DIR.
    Options:
        -L force symbolic links to be followed: resolve symbolic links in
        DIR after processing instances of '..'
        -P use the physical directory structure without following symbolic
        links: resolve symbolic links in DIR before processing instances
        of '..'
        -e if the -P option is supplied, and the current working directory
        cannot be determined successfully, exit with a non-zero status
        -@ on systems that support it, present a file with extended attributes
           as a directory containing the file attributes
    The default is to follow symbolic links, as if '-L' were specified.
    '..' is processed by removing the immediately previous pathname component
    back to a slash or the beginning of DIR.
    Exit Status:
    Returns 0 if the directory is changed, and if $PWD is set successfully when
    -P is used; non-zero otherwise..

Regarding the command syntax, one thing to note: If square brackets appear in the command syntax description, it means that these items are optional. | Indicates that the relationship between items is mutually exclusive. For the cd command above:

cd [-L|[-P[-e]]] [dir]

The syntax means that you can optionally add the -L or -P option after the cd command, and if the -P option also specifies the -e option, you can also follow the optional parameter dir after it.

Although the help document of the cd command is concise and clear, it is definitely not a tutorial. As we can see, it also mentions a lot of things that have not been mentioned! Don't worry, we will talk about it later.

5.3.2 --help—Display usage information

Many programs support the --help option, which can display a description of the syntax and options supported by the command. E.g:

[me@linuxbox ~]$ mkdir --help
Usage: mkdir [OPTION] DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
 
  -Z, --context=CONTEXT (SELinux) set security context to CONTEXT
Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx – umask
  -p, --parents     no error if existing, make parent directories as
                    needed
  -v, --verbose     print a message for each created directory
      --help        display this help and exit
      --version     output version information and exit
Report bugs to <[email protected]>.

Some programs may not support the --help option, but you can try it first. This usually produces an error message in which the same usage information can also be found.

5.3.3 man—Display the man page of the command

Most programs used on the command line provide a formal document called a manual or man page. There is a special paging program man that can browse such documents. Its usage is as follows:

man program

Among them, program is the name of the command corresponding to the man page to be browsed.

The format of the man page varies, but generally contains the following sections.

  • Title (the name of the man page).
  • Summary of command syntax.
  • Command description.
  • Name the list of options and their descriptions.

However, man pages usually do not contain examples, and are for reference, not tutorials. Let's try to browse the man page of the ls command:

[me@linuxbox ~]$ man ls

In most Linux systems, the man command uses the less command to display the manual page, so when browsing, all the familiar less commands still work.

The "man page" displayed by the man command is divided into sections, which not only cover user commands, but also system management commands, programming interfaces, file formats, and so on. Table 5-1 describes the organization of man pages.

Table 5-1 Organization structure of man pages

Section

content

1

User command

2

Programming interface for system calls

3

Programming interface of C library functions

4

Special files, such as device asynchronous and driver

5

file format

6

Games and entertainment, such as screen savers

7

Miscellaneous

8

System management commands

Sometimes we need to refer to certain sections of the man page to find what we need. It is more convenient when the file format to be searched is also the command name. If the section number is not specified, the pair that matches first will be displayed (it may be the first section). In order to specify the section number, it can be as follows:

man_section search_____term_

E.g:

[me@linuxbox ~]$ mkdir --help
Usage: mkdir [OPTION] DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
  -Z, --context=CONTEXT (SELinux) set security context to CONTEXT
Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx – umask
  -p, --parents     no error if existing, make parent directories as
                    needed
  -v, --verbose     print a message for each created directory
      --help        display this help and exit
      --version     output version information and exit
Report bugs to <[email protected]>.

This command will display a man page describing the format of the /etc/passwd file.

5.3.4 apropos-display a list of suitable commands

About the apropos command, you can search for possible matches in the list of man pages based on keywords. This method is rough, but sometimes it works. The following is an example of searching man pages with a keyword partition:

man_program_

The first section of each line in the output is the name of the man page, and the second section is the corresponding section. Note that the -k option of the man command has the same function as the apropos command.

5.3.5 whatis-display a brief description of the man page

The whatis command will display the names and single-line descriptions of man pages that match the specified keywords:

[me@linuxbox ~]$ whatis ls
ls                   (1) - list directory contents

Man pages that are difficult to read

The man pages provided by Linux and other UNIX-like systems are reference documents, not tutorials. , I carefully read the Bash man page to make sure that most of the topics are covered. If it is output, the densely packed text exceeds 80 pages, and the organizational structure it adopts definitely puzzles the novice.

However, the content of the manual page is accurate, the words are concise, and everything is covered in every detail.

5.3.6 info—Display the info list of the program

The GNU project provides an alternative to the man page for its own program: info. The Info page is displayed using a reader named info (appropriately). The info page also contains hyperlinks, which are quite similar to the web pages we usually see. Here is an example:

File: coreutils.info, Node: ls invocation, Next: dir invocation, Up:
Directory listing
10.1 'ls': List directory contents
==================================
The 'ls' program lists information about files (of any type, including
directories). Options and file arguments can be intermixed arbitrarily, as
usual.
   For non-option command-line arguments that are directories, by default 'ls'
lists the contents of directories, not recursively, and omitting files with
names beginning with '.'. For other non-option arguments, by default 'ls'
lists just the filename. If no non-option argument is specified, 'ls'
operates on the current directory, acting as if it had been invoked with a
single argument of '.'.
   By default, the output is sorted alphabetically, according to the
--zz-Info: (coreutils.info.gz)ls invocation, 63 lines --Top----------

The info program reads the info file, which is organized into individual nodes according to a tree structure, and each node contains a topic. The hyperlinks contained in the info file allow you to jump between nodes. Hyperlinks can be identified by the leading asterisk. Place the cursor on the hyperlink and press Enter to activate it.

Enter info and the program name (optional) to start the info program. Table 5-2 describes the commonly used control commands when displaying the info page.

Table 5-2 info command

command

operating

Show command help

Page Up or BackSpace

Show previous page

Page Down or Spacebar

Show next page

n

Display the next (next) node

p

Show the previous (previous) node

u

Display the current upstream parent node (up), usually a menu

Enter key

Enter the hyperlink where the cursor is

q

Quit

Most of the command-line programs we have discussed so far belong to the Coreutils package of the GNU project. Enter the following command:

[me@linuxbox ~]$ info coreutils

We will see a menu page with hyperlinks to various programs in the Coreutils package.

5.3.7 Documentation file

Many software packages installed in the system have their own documentation files, which are stored in the /usr/share/doc directory. Most of the document files are in plain text format and can be viewed using the less command. Some files are in HTML format and can be viewed with a web browser. We may encounter some files that end with a .gz extension. This shows that they are compressed by gzip. There is a special version of the less command in the gzip package, which is called zless, which can display the contents of the document file compressed by gzip.

5.4 Use alias to create your own commands

Now you can start to try to write the program! We will use the alias command to create our own commands. But before we get started, we need to show a little trick on the command line: you can use a semicolon as a separator to enter multiple commands at one time on the command line. It looks like this:

command1; command2; command3...

Let's look at an example:

[me@linuxbox ~]$ cd / usr; ls; cd -
bin games include lib local sbin share src
/home/me
[me@linuxbox ~]$

As you can see, we have placed 3 commands in one line. First change the current working directory to /usr, then list the contents of the directory, and finally return to the previous directory (using cd-), so that you are back to the starting point. Now, we use the alias command to turn the above command sequence into a new command. The first thing is to create an alias for the new command. Let's try test. But before that, it is best to check whether the name test is already occupied. To do this, use the type command:

[me@linuxbox ~]$ type test
test is a shell builtin

Sure enough, the name test is already taken, so try foo:

[me@linuxbox ~]$ type foo
bash: type: foo: not found

well! foo can be used, let's create an alias:

[me@linuxbox ~]$ alias foo='cd /usr; ls; cd -'

Pay attention to the wording of the alias command:

alias _name_='_string_'

After alias, we specify the alias, followed by (white space characters [[1]] are not allowed) is the equal sign, and then the string quoted in single quotes, which contains the content to be assigned to the alias. The defined alias can appear anywhere the Shell allows commands to appear. Let's try it:


[me@linuxbox ~]$ foo
bin games include lib local sbin share src
/home/me
[me@linuxbox ~]$

We can use the type command to view aliases:

[me@linuxbox ~]$ type foo
foo is aliased to 'cd /usr; ls; cd -'

The unalias command can delete aliases:

[me@linuxbox ~]$ unalias foo
[me@linuxbox ~]$ type foo
bash: type: foo: not found

For example, how the ls mentioned earlier adds color support through aliases:

[me@linuxbox ~]$ type ls
ls is aliased to 'ls --color=tty'

To know all the aliases defined in the system, use the alias command without any parameters. The following are some aliases defined by default in Fedora system. Use your brain to think about their role:

[me@linuxbox ~]$ alias
alias l.='ls -d .* --color=tty'
alias ll='ls -l --color=tty'
alias ls='ls --color=tty'

There is a small problem with defining aliases on the command line. When the Shell session ends, these aliases will disappear. In Chapter 11, we will learn how to add aliases to the system environment initialization file. Now that we have successfully taken a small step to the world of Shell programming, enjoy the moment!

5.5 Summary

We have learned how to get the command documentation, so try to look at the documentation of all the commands introduced before, study the other available options of these commands and practice!

This article is excerpted from: "Linux Command Line Encyclopedia  Second Edition"

 

This book gives a detailed introduction to the Linux command line. The content of the book includes 4 parts. The first part starts with the introduction of Shell to start the learning journey of command line basic knowledge; the second part describes the editing of configuration files and how to control the computer through the command line; The third part discusses common tasks and necessary tools; the fourth part comprehensively introduces Shell programming, readers can master the application of Linux commands by writing Shell scripts by hand, so as to realize the automation of common computing tasks. By reading this book, readers will have a more in-depth understanding of Linux commands and can apply them to actual work.
This book suits Linux beginners, Linux system administrators and Linux lovers to read.

Guess you like

Origin blog.csdn.net/epubit17/article/details/114655894