Shell program design, shell program design experiment

Source: Internet
Author: User
Tags call shell case statement

Shell program design, shell program design experiment

1. Basic concepts of shell scripts:

(1) Shell executes shell programs, which are usually called scripts.

(2) Shell is a program that interfaces between users and systems. It allows users to input the commands to be executed to the operating system.

(3) shell contains bash, csh, and other programs around the Linux kernel. (Figure 1-1)

(4) In most linux releases, the default shell program/bin/sh is actually a link to the Program/bin/bash.

Figure 1-1

2. Pipelines and redirection

2.1 redirect Input and Output

Eg: ls-1> 1.txt

Note:

Use <and> to redirect input and output. File descriptor 0 represents the standard input of a program, 1 represents the standard output, and 2 represents the error output.

You can use the> operator to append the output content to the original content.

Eg: ps> 1.txt

The following command redirects the standard output and standard error output to different files.

Eg: kill-HUP 1234> killout.txt 2> killerr.txt

Use the & operator to combine two outputs.

Eg: Kill-l 1234> killouterr.txt 2> & 1

Tip: The return code is generally stored in the linux "recycle bin"/dev/null to discard all output information.

Eg: Kill-l 1234>/dev/null 2> & 1

Redirect standard input.

Eg: More <killout.txt

More can accept the file name as a parameter.

2.2 Pipelines

Use the pipeline operator | to link processes. In linux, processes connected through pipelines can run at the same time, and can automatically coordinate with the transmission of data streams between them.

Eg: Ps> psout.txt Sort psout.txt> pssort. out

It can be solved by a command: Ps | sort> pssort. out

3. As a programming language

Directly entering shell scripts on the command line is a simple and quick way to test short code segments.

Eg:

$ For file in *

> Do

> If grep-l POSIX $ file

> Then

> More $ file

> Fi

> Done

When shell expects further input, the normal $ shell prompt will be changed to> prompt. You can keep inputting, by shell

To determine when the input is complete and immediately execute the script program. Shell also provides wildcard extension (globbing ). Available

Wildcard * can be used to match a string? To match a single character, while [set] allows matching any single character in square brackets

Character, [^ set] the content in the square brackets of the other party is retrieved, that is, matching any character that does not appear in the given character set. Expanded curly brackets

{} (Can only be used in some shells, including shells) allows you to place arbitrary strings in a collection, which has been extended by shell.

Eg:

Ls my _ {finger, toe} s

This command will list my_fingers and my_toe. It uses shell to check every file in the current directory.

3.1 create a script

Eg:

#! /Bin/sh

# First

# This file look through all the files in the current

# Directory for the string POSIX, and then pringts the names

# Those files to the standard output

For file in *

Do

If grep-q POSIX $ file

Then

Echo $ file

Fi

Done

Exit 0

The comment in the program starts with the # symbol and continues until the end of the line. Note that the first line #/bin/sh is a special form of annotation,

#! The character tells the system that the parameter followed by the same line is used to execute the program in this file. Because the script program is essentially

As a standard shell input, it can contain any linux Command that can be referenced by your PATH environment variable.

. There are two ways to set the script as executable.

The simplest method is to call shell and treat the script file name as a parameter,

Eg:/bin/sh first

Another type:

Eg: Chmod + x first./first

If you call first directly, the command not found may be printed. This is likely to happen because the PATH of the shell environment variable is not set.

Find the command to be executed in the current directory. To solve this problem, enter PATH = $ PATH:. or edit your. bash_profile.

File, add the command to the end of the file .. /First is used to tell shell the complete relative path of the script program.

4 shell syntax

4.1 variables in shell usually do not need to be declared in advance before using variables. You just use them to create them.

By default, all variables are treated as strings and stored as strings, even if they are assigned numerical values. Shell

And some tool programs will convert numeric strings into corresponding values as needed to operate on them. In shell, you can

Add a $ symbol before the variable name to access its content. When you assign values to a variable, you only need to use the variable name.

To be created automatically.

4.1.1 use quotation marks. Generally, parameters in the script file are separated by blank characters (for example, a space, a tab, or a line break ).

To include one or more blank characters in a parameter, you must enclose the parameter with quotation marks. If you put a $ variable expression in double quotation marks,

When the program executes this line, it will replace the variable with its value; if you put it in single quotes, it will not replace. You can also use the $ character

Add a \ character to remove its special meaning.

Eg:

#! /Bin/sh

Myvar = "Hi there"

Echo $ myvar

Echo "$ myvar"

Echo '$ myvar'

Echo \ $ myvar

Echo enter some text Read myvar

Echo '$ myvar' now equals $ myvar

Exit 0

4.1.2 Environment Variables

When a shell script starts execution, some variables are initialized according to the Environment setting values. These variables are generally named in uppercase letters.

The specific variables you create depend on your personal configuration. See Table 4-1.

 

4.1.3 parameter variables

Some additional variables will be created if the script program carries parameters during the call. Even if no parameters are passed, the environment variable $ # depends on

But its value is 0. See Table 4-2.

 

4.2 Conditions

Test or [command

In practice, most script programs use shell Boolean judgment commands or [or test. To enhance readability, when using the [command,

We also use the symbol] to end.

Eg:

If test-f fred. c

Then

...

Fi

You can also write it as follows:

If [-f fred. c]

Then

...

Fi

Tip: a space must be left between the [symbol and the condition to be checked.

The Test command can use three types of conditions:

(1) string comparison

(2) arithmetic comparison

(3) file-related condition tests

4.2.1 control structure if statement

Eg:

If condition

Then

Statements

Else

Statements

Fi

Elif statement:

Eg:

If condition

Then

Statements

Elif

Statements

Else

Statements

Fi

For statement

For variable in value

Do

Statements

Done

While statement

While condition

Do

Statements

Done

Until statement

Untilcondition

Do

Statements

Done

Case statement

Case variable in

Pattern [| pattern]...) statements ;;

Pattern [| pattern]...) statements ;;

...

Esac

Command list AND list

Syntax: Statements1 & Statements2 & Statements3 &&...

Execute each command from the left. If the previous command returns true, the next command on the right can be executed. AND as a whole, only in

If all commands in the list are successfully executed, the command is successfully executed. Otherwise, the command fails.

OR list Syntax:

Statements1 | Statements2 | Statements3 |...

Execute each command sequentially from the left. If the previous command returns false, the next command on the right can be executed. Statement Block

You can only use multiple statements in a single statement (such as in and or list). You can include them in {} to construct a statement block.

Eg:

Get_confirm &&{

Grep-v "$ cdcatnum" $ tracks_file> $ temp_file

Cat $ temp_file> $ tracks_file

Echo Add_record_tracks

}

Function-defined shell functions:

Function_name ()

{

 

Statements

}

You can use the return command to let the function return numeric values.

Foo ()

{

Echo JAY;

}

...

Result = "$ (foo )"

You can also use the local keyword to declare local variables in shell functions.

2. Shell code for sorting between file content lines

#! /Bin/bash

Sort-t = + 4

File

Note: "=" indicates to cut by = (Note: Only one character is allowed), and "+ 4" indicates to sort by the fifth item.

More parameters:

-R indicates descending order

-N indicates sorting by number size

-K indicates sorting by the field. The value 4.1 indicates that the first character of the 4th column starts and the value 5 indicates that the end of the 5th fields ends.

-T followed by a separator. The default value is space.

Example: sort-r-n-k4.1, 5 Function Description: delete a variable or function.

Syntax: unset [-fv] [variable or function name]

Note: unset is a shell built-in command that can delete variables or functions.

Parameters:

-F only deletes functions.

-V: only delete variables

 

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.