Basic analysis of Linux operating system (vii)--bash (Shell) Basics (1)

Source: Internet
Author: User
Tags aliases function definition posix readable terminates


In everyday English, the shell can be translated into shells, most of which means a device or structure that can protect the inner core. In computer science, the shell actually refers to a provider that can use the entire computer's resources through system calls or library calls.


It is both a command parser and a programming language. As a command parser, it can interpret and execute user-entered commands, and can automatically interpret and execute a series of commands that are pre-written and saved in a text file; As a programming language, the shell defines variables and parameters in particular, and provides many control structures in high-level languages. Includes loops and conditional branching, allowing us to use the shell in the same way as a high-level language, enabling it to handle applications in complex logical environments, improving its execution efficiency, and making it easier to perform its automation features.


Similar to the previous content, there are two concepts: interactive shell and non-interactive shell

The interactive mode is where the shell waits for your input and executes the commands you submit. This pattern is called interactive because the shell interacts with the user. This mode is also familiar to most users: Log in, execute some commands, log off. When you log off the login, the shell terminates the run.

The shell can also run in a different mode: non-interactive mode. In this mode, the shell does not interact with you, but instead reads the commands stored in the file and executes them. When it reads the end of the file, the shell terminates.


The main shell types in "UNIX like" are:

    • Bourne Shell (SH)

    • Korn Shell (Ksh)

    • Bourne Again Shell (bash)

    • POSIX Shell (SH)

    • C Shell (CSH)

    • Tenex/tops C Shell (tcsh)


=============================================================

Bourne Shell

The first important standard UNIX shell was introduced at the end of 1970 at V7 Unix (7th edition), and with its founding science and Technology Foundation platform-"National Meteorological Network Computing application Node Building" (2004dka50730) sponsor Stephen Named after the Bourne's name. The Bourne shell is a switch-type command interpreter and command programming language. The Bourne shell can be run as either the login shell or the login Shell's Child shell (Subshell). Only the login command can invoke the Bourne shell as a login shell. At this point, the shell reads the/etc/profile file and the $home/.profile file first. /etc/profile files are custom environments for all users, $HOME/.profile files for this user-defined environment. Finally, the shell waits for your input to be read.


C Shell

Bill Joy developed the C shell at the University of California in Berkeley in the early the 1980s. It is primarily intended to make it easier for users to use interactive features and to turn the grammatical structure of the ALGOL style into a C language style. It adds features such as command history, aliases, file name substitution, job control, and more.


Korn Shell

For a long time, there were only two types of shells for people to choose from, Bourne shell for programming, and C shell for interaction. To change the situation, the Bell lab David Korn developed the Korn shell. Ksh combines all of the C Shell's interactive features and incorporates the syntax of the Bourne shell. As a result, Korn shell is popular with users. It also adds features such as mathematical calculations, process collaboration (coprocess), inline editing (editing), and more. The Korn Shell is an interactive command interpreter and command programming language. It complies with the POSIX standard (portable Operating system, an international standard for an operating system). But POSIX is not actually an operating system (which should have been referred to as the POS standard, but later in order to cater to UNIX, and specifically added the IX suffix behind the POS, so called the POSIX standard), but a goal is to facilitate the application of porting standards, Enabling applications to be compiled across multiple platforms at the source program level is called possible.


Bourne Again Shell (bash)

Bash is part of the GNU program to replace the Bourne shell. It is used for GNU-based systems such as Linux. Most Linux (Red Hat,slackware,caldera) uses bash as the default shell, and when it runs SH, it actually calls bash, because SH is just a symbolic link to bash.


POSIX Shell

The POSIX shell is a variant of the Korn shell. The largest vendor currently providing POSIX shells is Hewlett-Packard. The HP-UX 11.0,posix Shell is/bin/sh.


--Quote from "Baidu Encyclopedia"

=============================================================

Bash is the default shell for most Linux systems and Mac OS X, which can run on most UNIX class operating systems and even be ported to the Cygwin system on Microsoft Windows to implement the POSIX virtual interface for Windows.
Bash's command syntax is a superset of the Bourne Shell (SH) command syntax. A large number of SH scripts can usually be executed directly in bash without modification, except for scripts that use special variables of SH or built-in commands. Many of Bash's command syntax comes from Korn shell (Ksh) and C Shell (CSH), such as command-line editing, command history, directory stacks, $RANDOM and $ppid variables, and POSIX command substitution syntax: $ (...).

When Bash is an interactive login shell, or a non-interactive shell with the--login option, it first reads and executes the commands in the/etc/profile file as long as it exists. After reading the file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile in the following order, and reads and executes the commands in this order from the first file that is present and readable. The--noprofile option can be used to block this behavior when the shell is started.

When a login shell exits, bash reads and executes the commands in these files as long as the ~/.bash_logout and/etc/bash.bash_logout files are present.

When an interactive shell is started, but not the login shell, bash reads and executes commands as soon as the ~/.BASHRC file exists. This behavior is prevented by using the--NORC option. --rcfile the "file" option forces Bash to read and execute the commands in the "file" files, not the ~/.BASHRC.

When bash starts in a non-interactive manner, such as running a shell script, bash looks for the bash_env variable in the environment variable, expands its value if it exists, and reads and executes it using the expanded value as the name of a file. The process of bash operation is like executing the following command:

If [-N "$BASH _env"]; Then

. "$BASH _env"

Fi

However, the value of the path variable is not used to search for that file name.

If Bash is called with the name SH, it attempts to imitate as much as possible the start-up process of the SH historical version, while also following the POSIX standard. When started as an interactive logon shell, or when a non-interactive shell is started with the--login option, it first attempts to read and execute the commands in the/etc/profile and ~/.profile files in this order. The--noprofile option can be used to block this behavior. When you use command sh to start an interactive shell, bash looks for the environment env variable, expands its value if it has already been defined, and then uses the expanded value as the name of the file to read and execute. The option--rcfile is invalid because the shell started with SH does not attempt to read and execute any other startup files. A non-interactive shell started with the name SH does not attempt to read any other startup files. When started with SH, Bash enters POSIX mode after reading the boot file.

When bash starts in POSIX mode, as with the--posix option, its startup files follow the POSIX standard. In this mode, the interactive shell expands the env variable and reads and executes the configuration file with the env variable value as the file name. No other startup files are read.

When bash is using its standard input to connect to the network, it tries to determine whether it was started by a remote shell daemon, typically rshd, or secure Shell daemon (sshd). If Bash discovers that it was started by rshd, and if the ~/.BASHRC file exists and is readable, it will read and execute the commands in it. If you start with the SH command, it will not do so. The--NORC option can be used to block this behavior, and the--rcfile option is used to force the reading of another file, but usually rshd will not allow them to be specified or be scheduled to start with those options.

If the shell is started with a valid user (group) ID instead of a real user (group) ID, and there is no-p option, the startup file is not read, and the Shell function is not inherited from the environment, if there is shellopts,bashopts in the environment variable, Cdpath and Globignore are ignored, the valid user ID is set to the real user ID. If the-P option is supported, the behavior at startup is similar, but the valid user ID is not reset.


For any Linux distribution operating system, bash is just an application, but it's a very special application. In Linux, for Bash itself, it is an external command. Let's take a look at the effect of this external command in a nutshell.

BASH: external command, command file storage path:/bin/bash, all called: GNU bourne-again SHell

Use format: Bash [options] [file]

Command Description:

Bash is an SH-compatible command language interpreter that can read and execute commands from a standard input or file. Bash also incorporates some of the useful features of Korn and C shell.

Bash is a consistent implementation of the shell and a utility that follows the IEEE POSIX specification. By default, bash is configured to be consistent with POSIX.


Common options:

-C String:

If you have the-C option, the command is read from "string". If a string is followed by a parameter (argument), they are assigned to the position parameter starting at $ A.

-I.:

If you have the-i option, the shell executes interactively (interactive).

-L:

option allows bash to launch in a way similar to the login shell.

-R:

If you have the-r option, the shell becomes restricted (restricted).

-S:

If there is the-s option, or if there are no parameters remaining after the option is processed, the command is read from the standard input. This option allows you to set the positional parameters when starting an interactive shell.

-D:

Prints a list of strings in double quotation marks leading to the standard output. This is the string in the script that is used to complete the language conversion when the current locale is not C or POSIX. This implies the-n option, and the command is not executed.

[-+] O [Shopt_option]

Shopt_option is an acceptable option for a shopt built-in command. If there is a shopt_option,-o will set the value of that option; +o cancels it. If Shopt_option is not given, the name and value of the shell option accepted by shopt will be displayed on the standard output. If the startup option is +o, the output is displayed as a format that can be reused as input.

--:

The "--" flag option ends and the rest of the options are forbidden to be processed. Any "--" parameters will be treated as filenames and parameters. Parameter-equivalent to this.


Bash also explains some of the multi-character options. These options must appear on the command line before the Word check item is recognized.

--debugger:

Prepares the debugger configuration file that was executed before the shell starts. Open the expand Debug mode and Shell feature tracking.

--dump-po-strings:

Equivalent to-D, but output is GNU GetText PO (Portable object) file format

--dump-strings:

Equivalent to-D

--help:

Display usage information in standard output and exit successfully

--init-file file

--rcfile file:

If the shell is interactive, execute the commands in file ~/.BASHRC instead of the standard personal initialization files

--login:

Equivalent to-l

--noediting:

If the shell is interactive, do not use the GNU ReadLine Library to read the command line.

--noprofile:

Does not read the system global startup file/etc/profile or any personal initialization file ~/.bash_profile, ~/.bash_login, or ~/.profile. By default, bash reads these files when it is called as a login shell

--NORC:

If the shell is interactive, the personal initialization file ~/.BASHRC is not read and executed. If the shell is called sh, this option is enabled by default.

--posix:

If the default action differs from the POSIX 1003.2 standard, change the behavior of Bash (POSIX mode).

--restricted:

The shell is limited.

--rpm-requires:

Produce a list of files that are required for the shell script to run. This implies-N. Limited by the same limitations as compile-time error detection, backticks, [] tests, and evals will not be parsed and some dependencies may be lost.

--verbose:

Equivalent to-V

--version:

The standard output displays the version information for this bash instance and exits successfully.

Parameters:

If the option is still left by the parameter after processing, and the-s or-c option is not provided, then the first parameter is assumed to be the name of the file containing the shell command. If bash starts in this way, the $ is set to the name of the file, and the positional parameters are set to the remaining parameters. Bash reads and executes commands from this file, and then exits. The exit status of Bash is the exit state of the last command in the footstep. If no command is executed, the exit status is 0. First try to open the file in the current directory, and then, if the file is not found, then the shell will search the directory in path in order to find the script file.


Some of the definitions in the shell:

The following definitions are common in the remainder of the document.

Blank: A Space or Tab

Word: A string that is seen by the shell as a single unit, also known as a token.

Name: A string that can only start with a letter or underscore, and includes only alphanumeric and underlined characters, also known as identifiers.

Metacharacter: A meta-character, a character that, if not referenced, will be the delimiter of the word, one of the following characters:

| &; () < > Space tab

Control operator: Controls operator, a token with control function, one of the following symbols:

|| & &&;;; ( ) | <newline>


Since the shell is so important and so indispensable, how should we use the shell? In fact, it is very simple to learn to use the shell and you have to understand what features the shell provides to the operator.


Let's take a look at bash as an example to introduce its basic features:

One, the order explanation:

This feature can be said to be any kind of shell or club any interface program must have the basic functions, and even should be said that its innate mission.

So how does bash explain the order?

1. In bash, Bash tries to interpret the command only by typing a carriage return;

2. After typing the carriage return, bash attempts to segment the entire command line with whitespace characters, and Bash will assume that the leftmost segment is the command to be executed;

3.bash after you have identified a string that might be a command, you need to know whether this is an internal command or an external command. The so-called internal command, which is the command that comes with bash, is usually loaded into memory after bash is running, because such commands are part of the bash, and so-called external commands are the commands that are stored in some chunks of external memory by installing other applications. There's no direct relationship with bash. If this is an internal command, bash can run directly, and then return execution results and execution status information, and if this is not an internal command, bash invokes the built-in path variable that holds the executable binary, reading the contents of the variable. To find out if there is a file with the same name as the command executed this time, if any, execute it, if not, it will report an error message such as:-bash:commamd:command not found. The "command" may be replaced with the command being executed. As shown in the following example:

[Email protected] ~]# Sss-bash:sss:command not found

4.bash when judging the type of command and giving an explanation, the other fields in the entire command line are sent as a selection and parameters to the command, and if they are correct, the command executes correctly, and bash outputs the execution of the command to the standard input in the format required by the command. But if such an option or parameter is not correct or is not available, you will also need to treat it in the following two cases:

1) If it is an internal command, bash will always be in charge to help the command report error messages;

2) If it is an external command, it is not bash can decide, usually this time, will be executed by the application to determine whether the options and parameters are correct, if not correct, the application will report the error message.

3) Whether it is an internal command or an external command, even if the external command was launched by Bash, Bash is responsible for whether the command is successful or not. At the end of execution, Bash uses an exit code to identify its execution status information and save that state information to a name of "?". In a special variable. If you want to see this state, we can use the general variable content reading method: Echo $? Can. Generally speaking, the return value of such a command execution state is represented by an integer of 0-255, where:

0: Indicates that the command executed successfully

1, 2, 127: The default error code for bash

3-126: User-Customizable error codes

128-255: A command quits abnormally, but exits because a signal is received, so the status return value is 128+n, where "N" indicates the number of the signal received by the command.


Please refer to the following example:

[Email protected] ~]# CD-A-BASH:CD:-a:invalid optioncd:usage:cd [-l|-p] [dir]

(the option for internal commands is wrong here)

[Email protected] ~]# CD/TESTTT-BASH:CD:/testtt:no such file or directory

(The parameter for the internal command is wrong here)

[Email protected] ~]# echo $?1

(Here is the status return value for the command execution.) In general, if the return value is "0", the command executes successfully or the command execution fails)

[[email protected] ~]# ls--pls:unrecognized option '--p ' Try ' ls--help ' for more information.

(option is wrong here)

[Email protected] ~]# ls/testttls:cannot access/testtt:no such file or directory

(parameter error is here)

[Email protected] ~]# echo $?2

(Here is the status return value for the command execution.) In general, if the return value is "0", the command executes successfully or the command execution fails)


Second, the command alias


Bash gives us the privilege of creating aliases for commands, whether it's a system administrator or an ordinary user, and you can define the alias command, and the method is simple:

1. You can use the alias command to define the aliases command;

2. You can use the Unalias command to cancel an alias command that has already been defined;

3. Whether you cancel using the alias command definition or the Unalias command, the bash run parameter in memory is changed, so as long as bash is off, the feature is invalidated. Therefore, in order to make the alias command permanent, you can write such a definition in the. bashrc file in your home directory, each user has this file in their home, fair trade.

If the first word of each simple command is not quoted, bash checks its implementation to see if the command has an alias for a command. If so, the command will be replaced by the corresponding alias. The characters "/", "$", "'" and "=" and the shell's meta characters for any shell cannot appear in the alias. The replaced text content can contain any valid shell input, including the Shell's metacharacters. The first word of the replacement text is also checked for aliases. However, if it is the same as the alias that was replaced, it will not be replaced a second time. This means that LS can be used as an alias for Ls-f, and bash does not recursively expand the replacement text. If the last character of the alias is a white-space character, the next word after the alias in the command is checked for alias expansion.


If the shell is not interactive, the alias will not expand unless the expand_aliases option is set with the built-in command shopt.

The definition of aliases and the rules used are confusing. Bash always reads the input of a line completely before executing any of the commands in a row. Aliases are expanded when the command is read, not at execution time. Therefore, if the alias definition is on the same line as another command, it will not work unless the next line is read in. After the alias definition, the commands in the same row are not affected by the new alias. This behavior is controversial when the function is executed because the alias substitution defined in the function occurs when the alias is read, not when the function is executed, because the function definition itself is a compound command. As a result, aliases defined in the function will only take effect if the function finishes executing. For insurance purposes, you should always place the alias definition on a separate line and not use alias in the composite command.

Aliases are useful in some cases, because depending on this feature, we can:

1. Simplify complex commands, such as:

[[email protected] ~]# alias l.= ' ls-d. *--color=auto ' [[email protected] ~]# alias ll= ' ls-l--color=auto ' [[Email protect Ed] ~]# alias ls= ' ls--color=auto '

2. Secure dangerous commands, such as:

[[email protected] ~]# alias cp= ' cp-i ' [[email protected] ~]# alias mv= ' mv-i ' [[email protected] ~]# alias rm= ' Rm-i '

3. Define different styles of commands according to your preferences and usage habits, such as:

[[email protected] ~]# alias cdnet= ' cd/etc/sysconfig/network-scripts/' [[email protected] ~]# alias viht= ' vim/etc/httpd /conf/httpd.conf '

(To be Continued ...)

This article is from the "home of the Ops" blog, so be sure to keep this source http://zhaotianyu.blog.51cto.com/132212/1785288

Basic analysis of Linux operating system (vii)--bash (Shell) Basics (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.