Shell programming getting started teaching documents

Source: Internet
Author: User
Tags case statement

Getting started with shell programming
I. Shell Customization
Shell is the interface between the user and the Linux operating system. Linux has multiple shells. Bash is used by default.
As the operating system shell, the Linux system shell provides users with the interface to use the operating system. It is a general term for the command language, command Interpretation Program, and programming language.
Shell is a command language interpreter. It has its own built-in shell command set, and shell can also be called by other applications in the system. The commands entered by the user at the prompt are explained by Shell and then passed to the Linux core.
Another important feature of shell is that it is an interpreted programming language. The shell programming language supports most program elements that can be seen in high-level languages, such as functions, variables, arrays, and program control structures. The shell programming language is easy to learn. Any command that can be typed in a prompt can be put into an executable shell program.

Ii. shell programming script Process
Note: When writing a script:
The program must start with the following line (the first line of the file must be placed ):
#! Bin/sh
Symbol #! The parameter used to tell the system is the program used to execute the file. In this example, we use/bin/sh to execute the program. When you edit a script, you must also run it.
To make the script executable: Compile chmod + x filename to run it with./filename.

III. Basic shell statements
The basic syntax of shell is how to input commands to run programs and how to communicate between programs through shell parameters.
Three specific cases:
Redirection
Pipeline Pipe
Front-end and back-end
For more information, see (1-1.doc ).
4. Shell Variables
System Variables
User variable
Environment Variable

<1> System Variables
There are not many common shell system variables, but they are very useful, especially when detecting some parameters. The following are common shell system variables:

$ N $1 indicates the first parameter, and $2 indicates the second parameter...
$ # Number of command line parameters
$0 name of the current program
$? The return code of the previous command or function.
$ * Save all parameters in the form of parameter 1 parameter 2...
$ @ Save all parameters in the form of "parameter 1" "parameter 2 "...
$ PID of the Program (process ID)
$! PID of the previous command
$ N $ #$0 $?
Example: see (1-2.doc)

<2> shell user Variables
No matter how many system variables there are, it is always not enough for demand. User variables are the most commonly used variables, which are also very simple to use.
A user-defined variable must consist of letters, numbers, and underscores. the first character of the variable name cannot be a number. Like other UNIX names, the variable name is case sensitive. you can assign values to user variables as follows:
Name = "wanggou" must be preceded by a $ symbol when referencing a variable. You can assign values between variables, for example:
Name = "wanggou"
Wanggou = $ name
Echo "Hello $ wanggou! "
The output result should be clear: Hello wanggou!
Note: there should be no space between the variable and '=', and neither '=' nor the value. Otherwise, shell will not consider the variable as being defined. With the basic usage, you can start your programming work completely.

<3> shell Environment Variables
Shell environment variables are accepted by all Shell programs. When the shell program runs, it receives a set of variables, which are environment variables. For more information about common environment changes, see Appendix 1-3.doc>.
The most important of these variables is path.
How to define new environment variables:
To define new environment variables, use export. See the following example:
Export my_name = wanggou
Export Path =/home/wanggou/bin: $ path

<4> perform arithmetic operations on Shell Variables

V. Shell statements
Condition Statement
The condition statements in Shell programs mainly include the if statement and the case statement;
Loop statement
Common shell loop statements include for loop, while loop, and until loop.

<1> test command
Unlike traditional languages, shell is used to specify the condition value instead of a Boolean expression but a command and string. (Before learning the conditional statement, it is necessary to have a general understanding of the test command .)
The test command is used to check whether a condition is true. It can be used to test values, characters, and files.
For more information, see (1-5.doc ).

<2> For Loop
For Loop
Format: for VAR in arg1 arg2... argn
Do command
....
Command
Done
Note: VaR is the variable name, And the arg1-n is the value list. Between do and done is the command list.
Example: see (1-6.doc)

<3> WHILE LOOP
Both the while and until commands use the return status value of the command to control the loop.
Format:

<4> loop statement until Loop
<5> If
<6> Condition Statement case
Syntax: Case string in value 1 | value 2) operation: Value 3 | value 4) operation: value 5 | value 6) operation: *} Operation :: esac case is used to perform the operation after the value when the string is the same as a value. If the same operation has multiple values, use "|" to separate the values. At the end of each case operation, there are two ":" And a semicolon is required.
Example: see (1-10.doc ).

<7> unconditional control statement
Break is used to terminate the execution of the current loop immediately, while contiune is used to start the execution of the next loop immediately without executing the statements following the loop. These two statements are valid only when they are placed between do and done.
Example: see (1-11.doc ).

6. Function Definition
A shell function is a method for organizing commands for subsequent operations. It uses a single name to name these command groups or routine. In shell or script, the process name must be unique. All commands used to organize functions are executed just like common commands. When a function is called using a simple command name, commands related to the function are executed. The function must be declared and then executed in shell: no new process will be created to interrupt this command.
NOTE: Special built-in commands are used to search for Shell functions first. Special built-in commands: Break,:,., continue, Eval, exec, exit, export, readonly, return, set, shift, trap, and unset.

VII. Function Form
The function uses the following two forms.
Function function {commands ;}
Or
Function () {commands ;}
Both define a shell function
Note: built-in function commands are optional. However, if you do not use them, you must add parentheses after the function name.
8. location parameters in the function
Shell functions: they can accept parameters, they can use only valid variables in the function (using local built-in local) and they can return parameters to the caller.
When the function starts to be executed, the parameter of the function becomes the location parameter during execution. Special parameter # updated to reflect the change. The location parameter 0 is not changed. The bash variable funcname is set as the function name during function execution.
If the built-in return is executed in the function, after the call is completed, the function is complete and the next command is executed. After the function is complete, the value of the location parameter and the value of the special parameter # are reset to the value before the function is executed. If return is assigned to a numeric parameter, the return state is returned. Example: see (1-13.doc ).

9. display functions
All functions recognized by the current shell can be displayed using set. Functions are retained after they are used, unless they are unset after use.

9. Application of functions in scripts
<1>. Recycling
A large number of scripts in your system use functions to process a series of commands in a structured manner. In some Linux systems, for example, you can find the/etc/rc. d/init. d/functions definition file, and the source file is in all the initialization scripts. To use this method, you only need to write it once. Common tasks such as checking whether the process is running, starting or stopping a daemon process, and so on. If some tasks still need to be executed once, the code can be reused.
Example: see (1-14.doc ).
<2>. Set the path
<3>. Remote Backup

 

 

See the example below

1-1.doc
(1) Input/Output redirection
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 standard output and standard error output results 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.
1-2.doc
#! /Bin/bash
# This file is used to explain the shell system variable.
Echo "the number of parameter is $ #";
Echo "The return code of last command is $? ";
Echo "The Script Name is $0 ";
Echo "the parameters are $ *";
Echo "/$1 = $1;/$2 = $2 ";
1-4.doc
For example:
$ Expr 2 + 1
Result: 3
$ Expr 5-3
The result shows: 2 if one of the expr parameters is a variable, replace the variable name with the variable value before the expression is calculated.
$ Int = 3
$ Expr $ int + 4
Result: 7
Users cannot simply use "*" for multiplication. If the input is:
$ Expr 4*5
The system will report an error because the shell will replace the file name first when it sees. The correct format is:
$ Expr 4/* 5
Result: 20
Multiple arithmetic expressions can be combined, for example:
$ Expr 5 + 7/3
Result: 7
The operation order is multiplication, division, and addition or subtraction. To change the operation order, you must use the "'" number, such:
$ Int = 'expr 5 + 7'
$ Expr $ int/3
Result: 4
Or:
$ Expr 'expr 5 + 7'/3
Result: 4
Note: The red "$" indicates a common user.
1-5.doc
(1) numerical test:
-EQ: true if it is equal
-Ne: true if not equal
-GT: true if the value is greater
-Ge: true if the value is greater than or equal
-Lt: true if the value is smaller
-Le: true if the value is less than or equal
(2) string test:
=: Equal to true
! =: True if not equal
-Z string: the pseudo-String Length is true.
-N string: the string length is true if it is not pseudo.
(3) file test:
-E file name: true if the file exists
-R file name: true if the file exists and is readable
-W file name: true if the file exists and can be written.
-X file name: true if the file exists and can be executed
-S file name: true if the file exists and contains at least one character
-D file name: true if the file exists and is a directory
-F file name: true if the file exists and is a normal file
-C file name: true if the file exists and is a special character file
-B file name: true if the file exists and is a special file.
Note: In addition, Linux also provides the , Or ("-O), non ("-a ") three logical operators are used to connect test conditions, the priority is:"!" Highest, followed by "-a", and "-o.
1-6.doc
#! /Bin/bash
For wangluo in wanggou wangguan
Do
Echo $ wangluo
Done
1-7.doc
Example: Use "while" to calculate the square of 1 to 5
#! /Bin/bash
Int = 1
While [$ int-le 5]
Do
Sq = 'expr $ int // * $ int'
Echo $ SQ
Int = 'expr $ int + 1'
Done
Echo "Congratulations! Now let's take a look. "
1-8.doc
Example: Calculate the square of 1-5 using the until Structure
#! /Bin/bash

Int = 1

Until [$ int-GT 5]
Do
Sq = 'expr $ int // * $ int'
Echo $ SQ
Int = 'expr $ int + 1'
Done
Echo "succeeded. Congratulations !! Continue to work hard. "
1-9.doc
#! /Bin/bash
If ["$ shell" = "/bin/sh"]; then
Echo "your login shell is the sh"
Else
Echo "your login shell is not bash but $ shell"
Fi
1-10.doc
#! /Bin/bash
Case $ user in
Beichen)
Echo "you are Beichen !";;
Liangnian)
Echo "you are liangnian"; // note that there is only one semicolon
Echo "Welcome !";; // Here are two semicolons
Root)
Echo "you are root! : Echo welcome !";; // Write the two commands in one line and use a semicolon as the Separator
*)
Echo "who are you? $ User ?";;
Esac
The output result is:
You are root!
Welcome!
1-11.doc
#! /Bin/bash
Echo "What is your favorite OS? "
Select VaR in "Linux" "GNU Hurd" "Free BSD" "other"; do
Break
Done
Echo "you have selected $ Var"

Note: The break is valid only when it is placed between do and done.
1-12.doc
#! /Bin/bash
Function func (){
Echo $1
Echo $2
Return 1
}
Func "hello" "What is your name? "
1-13.doc
# Vi jiaoben
#! /Bin/bash echo "this script demonstrates function arguments ."
Echo
Echo "positional parameter 1 for the script is $1 ."
Echo
Test ()
{
Echo "positional parameter 1 in the function is $1 ."
Return_value = $?
Echo "the exit code of this function is $ return_value ."
} Test other_param
Exit save
Chmod A + x jiaoben # Grant executable permissions
./Jiaoben understand? # Run jiaoben
1-14.doc
# Check if $ PID (cocould be plural) are running
Checkpid (){
Local I

For I in $ *; do
[-D "/proc/$ I"] & Return 0
Done
Return 1
}
Note: This function is reused in other functions that are reused in the same script. Daemon processes, for example, are mostly used in the Start script for starting a service process.
1-15.doc
Pathmunge (){
If! Echo $ PATH |/bin/egrep-Q "(^ |:) $1 ($ |:)"; then
If ["$2" = "after"]; then
Path = $ path: $1
Else
Path = $1: $ path
Fi
Fi
}

# Path manipulation
If ['id-U' = 0]; then
Pathmunge/sbin
Pathmunge/usr/sbin
Pathmunge/usr/local/sbin
Fi

Pathmunge/usr/x11r6/bin after

Unset pathmunge
Note: This function sets the first parameter as the path name. If the path name is not in the current path, add it. The second parameter passed to the function defines whether the path is before or after the current path.
Common users only add/usr/x11r6/bin to their paths. When the root user obtains additional directories containing system commands. After use, the function is unset, so it does not exist.
1-16.doc
On Sunday, only bupbash runs.
#/Bin/bash

Logfile = "/nethome/tille/log/backupscript. log"
Echo "Starting backups for 'date'"> "$ logfile"

Buplinux ()
{
Dir = "/nethome/tille/XML/DB/Linux-basics /"
Tar = "linux.tar"
Bzip = "$tar.bz2"
Server = "Rincewind"
Rdir = "/var/www/intra/tille/html/training /"

Cd "$ dir"
Tar CF "$ tar" src/*. xml src/images/*. PNG src/images/*. EPS
Echo "compressing $ tar..."> "$ logfile"
Bzip2 "$ tar"
Echo "... done."> "$ logfile"
Echo "copying to $ server..."> "$ logfile"
SCP "$ bzip" "$ server: $ rdir">/dev/null 2> & 1
Echo "... done."> "$ logfile"
Echo-e "done backing up Linux Course:/nsource files, PNG and EPS images./nrubbish removed."> "$ logfile"
RM "$ bzip"
}

Bupbash ()
{
Dir = "/nethome/tille/XML/DB /"
Tar = "bash.tar"
Bzip = "$tar.bz2"
Files = "bash-programming /"
Server = "Rincewind"
Rdir = "/var/www/intra/tille/html/training /"

Cd "$ dir"
Tar CF "$ tar" "$ Files"
Echo "compressing $ tar..."> "$ logfile"
Bzip2 "$ tar"
Echo "... done."> "$ logfile"
Echo "copying to $ server..."> "$ logfile"
SCP "$ bzip" "$ server: $ rdir">/dev/null 2> & 1
Echo "... done."> "$ logfile"

Echo-e "done backing up bash Course:/N $ files/nrubbish removed."> "$ logfile"
RM "$ bzip"
}

Day = 'date + % W'

If ["$ Day"-lt "2"]; then
Echo "It is 'date + % A', only backing up bash course."> "$ logfile"
Bupbash
Else
Buplinux
Bupbash
Fi

Echo-e "remote backup 'date' success/n ----------"> "$ logfile"

 

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.