Linux shell programming

Source: Internet
Author: User
Shell itself is a program written in C language, which serves as a bridge between users using Linux. Shell is both a command language and a programming language. As a command language, it interactively interprets and executes user-input commands. as a programming language, it defines various variables and parameters and provides many

Shell itself is a program written in C language, which serves as a bridge between users using Linux. Shell is both a command language and a programming language. As a command language, it interactively interprets and executes user-input commands. as a programming language, it defines various variables and parameters, it also provides many control structures that are available in advanced languages, including loops and branches. Although it is not part of the core of Linux, it calls most of the core functions of the system to execute programs, create files, and coordinate the running of various programs in parallel. Therefore, shell is the most important utility for users. it is the key to make good use of the Linux system by thoroughly understanding and mastering the features of shell. It can be said that the proficiency of shell reflects the user's proficiency in Linux.

I. What is shell?

After a user logs on to Linux, the system initialization program init runs a shell program for each user. So what is shell? To be exact, shell is a command line interpreter that provides users with an interface system-level program that sends requests to the Linux kernel to run the program, you can use shell to start, suspend, stop, or even write some programs.

When you use Linux, you can use commands to complete the required work. A command is a basic unit of dialog between a user and a shell. it consists of multiple characters and ends with a line break. Shell explains the commands entered by the user, just as command.com in DOS does. The difference is that in DOS, command.com has only one, in Linux, there are several popular shells, each of which has its own merits. Generally, bash is used as the default shell in Linux.

2. several popular shells

Currently, popular shell types include ash, bash, ksh, csh, and zsh. you can use the following command to view your own shell types:

# Echo $ SHELL

$ SHELL is an environment variable that records the shell type used by the user. You can run the following command:

# Shell-name

To another shell. here, shell-name is the name of the shell you want to use, such as ash. This command starts another shell for the user. This shell is called a lower-level shell or a sub-shell after the shell is first logged on. Run the following command:

$ Exit

You can exit this sub-shell.

The reason for using different shells is that they all have their own characteristics. The following is a brief introduction:

1. ash

Ash shell is compiled by Kenth almsource. a small shell that occupies the least system resources in Linux contains only 24 internal commands, which makes it inconvenient to use.

2. bash

Bash is the default shell used in Linux. it is jointly completed by Brian Fox and Chet Ramey. it is short for Bourne Again Shell and has a total of 40 internal commands. Linux uses it as the default shell because it has the following features:

(1) you can use a function similar to doskey under DOS, and use the direction keys to view and quickly enter and modify commands.

(2) the command starting with a string is automatically provided by searching for matching.

(3) It includes its own help function. you only need to enter help at the prompt to get the help.

3. ksh

Ksh is short for the Korn shell. it is written by Eric Gisin and contains 42 internal commands. The biggest advantage of this shell is that it is almost completely compatible with the commercial release ksh, so that you can try the performance of the commercial version without spending money to buy the commercial version.

4. csh

Csh is a large Linux kernel. it is compiled by a total of 47 authors represented by William Joy and contains 52 internal commands. This shell actually points to a shell like/bin/tcsh, that is, csh is actually tcsh.

5. zch

Zch is one of the largest shell in Linux. it is completed by Paul Falstad and has 84 internal commands. For general purposes, there is no need to install such a shell.
3. shell program design (basic)

In fact, the interactive interpretation and execution of user input commands as a command language is only one aspect of the shell function, shell can also be used for program design, it provides a variety of methods to define variables and parameters as well as program control structures. Using shell programming is similar to a batch processing file in DOS, called a shell script, or a shell program or shell command file.

1. Basic shell syntax

The basic syntax of shell is how to input commands to run programs and how to communicate between programs through shell parameters.

(1) input/output redirection

In Linux, each process has three special file description pointers: standard input (0), standard output, file description pointer is 1), standard error output (standard error, File description pointer is 2 ). These three special file description pointers enable the process to normally receive input from the standard input terminal and display the output from the standard terminal, linux also provides users with the ability to use common files or pipelines to replace these standard input and output devices. In shell, you can use ">" and "<" to redirect input and output. For example:

Command> file: redirects the command output to a file.

Command> & file: redirects the standard error output of the command to a file.

Command> file: append the standard output result to the file.

Command >>> & file: append the structure of the standard output and standard error output to the file.

Command <p>

(2) Pipeline pipe

Pipe can also replace the standard input output and standard error output, so that the output of a program can be sent to the input of another program. The syntax is as follows:

Command1 | command2 [| command3. ..]

It can also be sent to the pipeline together with the standard error output:

Command1 | & command2 [| & command3. ..]

(3) foreground and background

In shell, a new process can be executed by using the symbols ";" and "&" after the command respectively in the foreground and background. The syntax is as follows:

Command

Generate a foreground process. The next command can only be entered after the command is run.

Command &

Generates a background process that runs in the background and can input other commands.

2. Shell program variables and parameters

Like an advanced programming language, shell also provides instructions and the ability to use variables. For shell, the values of all variables are a string, and the shell program uses $ var to reference the value of the variable named var.

Shell has the following basic types of variables:

(1) environment variables defined by shell

At the beginning of execution, shell has defined some variables related to the system's working environment. you can also redefine these variables. common shell environment variables include:

HOME: The full path name used to save the registration directory.

PATH: used to save the directory PATH names separated by colons. shell searches these directories in the order given in the PATH variable. The first executable file with the same name as the command will be executed.

TERM: the type of the terminal.

UID: the identifier of the current user. The value is a string consisting of digits.

PWD: the absolute path name of the current working directory. The value of this variable varies with the use of the cd command.

PS1: primary prompt. for privileged users, the default primary prompt is "#". for common users, the default primary prompt is "$ ".

PS2: when the shell receives the user's input command, if the user enters "" at the end of the input line, then press Enter, or, when the shell determines that the command entered by the user is not over when the user presses the enter key, the pop-up prompt is displayed, prompting the user to continue entering the rest of the command. the default pop-up prompt is "> ".

(2) user-defined variables

You can define your own variables according to the following syntax rules:

Variable name = variable value

Note that "$" should not be added before the variable name when defining the variable, and "$" should be added before the variable name when referencing the variable content "; when assigning values to variables, spaces must not be left on both sides of the equal sign. if the variable itself contains spaces, the entire string should be enclosed in double quotation marks.

When writing a shell program, we recommend that you use uppercase letters to indicate all variable names to distinguish them from command names.

Sometimes we want to explain a variable and set it to a specific value without changing its value. this can be ensured by the following command:

Readly variable name

At any time, the created variables are only local variables of the current shell, so they cannot be used by other commands or shell programs run by the shell, the export Command provides a local variable to other commands executed by shell in the format:

Export variable name

You can also use the export command when assigning values to variables:

Export variable name = variable value

Variables described in export can be accessed in all commands or programs run after shell.

(3) location parameters

A location parameter is a variable that is determined by its location in the command line that calls the shell program. it is a parameter entered after the program name. Location parameters are separated by spaces. shell replaces $1 with the first location parameter in the program file, and the second with $2, and so on. $0 is a special variable whose content is the file name of the current shell program. Therefore, $0 is not a location parameter, $0 is not included when all the current location parameters are displayed.

(4) predefined variables

Predefined variables are similar to environment variables and are also defined at the beginning of shell. The difference is that users can only use these variables according to shell definitions, you cannot redefine it. All predefined variables are composed of the $ operator and another symbol. common shell predefined variables include:

$ #: Number of location parameters

$ *: Content of parameters at all locations

$? : Status returned after the command is executed

$: Process ID of the current process

$! : The last process number running in the background

$0: name of the currently executed process

Where, "$ ?" This command is used to check whether the execution of the previous command is correct (in Linux, the exit status of the command is 0, indicating that the command is correctly executed, and any non-0 value indicates that the command has an error ).

The most common use of the '$' variable is to use it as the name of a temporary file to ensure that the temporary file will not be repeated.

(5) parameter substitution variables

Shell provides the parameter replacement capability so that you can assign different values to variables based on different conditions. Parameter replacement

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.