Shell programming ·····

Source: Internet
Author: User
Shell programming ·-Linux general technology-Linux technology and application information, the following is a detailed description. 1. Basic shell knowledge
Developed by Stephen Bourne at the Bell lab
Suggestion: use man sh to view improvements or features on UNIX.

(1) shell prompt and its environment
/Etc/passwd file
Prompt: $
/Etc/profile $ HOME/. profile
(2) shell execution options
-N: test the shell script syntax structure. Only shell scripts are read but not executed.
-X: Enter the tracking mode to display each command executed for scheduling.
-A Tag all variables for export
-C "string" reads commands from strings
-E non-interactive mode
-F disable the shell file name generation function
-H locate and remember functions as defind
-I Interaction Mode
-K read command parameters from Environment Variables
-R restrictions
-S: Read commands from standard input
-T execute the command and exit (shell exits)
-If undefined variables are used in replacement, the u is incorrect.
-V verbose: displays the shell input line.

These options can be used together, but some of them obviously conflict with each other, such as-e and-I.

(3) restricted shell (Restircted Shell)
Sh-r or/bin/rsh

You cannot perform the following operations: cd, change PATH, specify full PATH name, and output redirection. Therefore, you can provide
Good control and security mechanisms. Generally, rsh is used for application users and dial-up users.
. The main directory of a restricted user cannot be written.

Insufficient: if the user can call sh, the rsh restriction will not work. In fact, if the user
The program calls the shell, and the rsh restrictions will no longer work.

(4) use set to change shell options
You can use the set command at the $ prompt to set or cancel shell options. Use-set options, + cancel the corresponding
Option, most UNIX systems allow a, e, f, h, k, n, u, v, and x to switch/cancel.

Set-xv
Start tracing method. All commands and replicas are displayed, and input is also displayed.
Set-tu
Disable the check for undefined variables during replacement.

Use echo $-to display all configured shell options.


(5) User Startup File. profile
PATH = $ PATH:/usr/loacl/bin; export PATH

(6) shell Environment Variables
CDPATH is used to find the path of the cd command.
HOME/etc/passwd file
IFS Internal Field Separator. The default value is space, tab, and line feed.
Use MAIL/var/mail/$ USERNAME mail and other programs
PATH
PS1, PS2 default prompt ($) and line feed prompt (>)
TERM terminal type. Common types include vt100, ansi, vt200, and xterm.

Example: $ PS1 = "test:"; export PS1
Test: PS1 = "$"; export PS1
$ Echo $ MAIL
/Var/mail/username
(7) reserved characters and their meanings
$ Start of shell variable name, such as $ var
| Pipeline, which transfers the standard output to the standard input of the next command
# Start Annotation
& Execute a process in the background
? Match one character
* Matches 0 to multiple characters (different from DOS, which can be used in the middle of the file name and contain .)
$-Use set and the flag passed to shell during execution
$! Process ID of the last sub-process
$ # Number of parameters passed to shell script
$ * Parameters passed to shell script
$ @ All parameters. Some parameters are enclosed in double quotation marks.
$? Return code of the previous command
$0 name of the Current shell
$ N (n: 1-) Location Parameter
$ Process Identifier Number (PID)
> File output redirection
> Fiile output redirection, append

Escape characters and single quotes:
$ Echo "$ HOME $ PATH"
/Home/hbwork/opt/kde/bin:/usr/local/bin:/usr/X11R6/bin:
$ Echo '$ HOME $ Path'
$ HOME $ PATH
$ Echo $ HOME $ PATH
$ HOME/opt/kde/bin:/usr/local/bin:/usr/X11R6/bin:/home/hbw
Ork/bin

Others:
$ Dir = ls
$ Dir
$ Alias dir ls
$ Dir

Ls> filelist
Ls> filelist
Wc-l/dev/rmt/0 h

The purpose of writing a program is to program it once and use it multiple times )!

$ Cat> backup. sh
Cd/home/hbwork
Ls * | cpio-o>/dev/rmt/0 h
^ D

Run:
$ Sh backup. sh

Or:
$ Chmod + x backup. sh
$./Backup. sh

Tip: add necessary comments to shell scripts for later reading and maintenance.

(2) shell is a (programming) Language
Like traditional programming languages, shell provides many features that enable your shell script
Programming is more useful, such as data variables, parameter passing, Judgment, process control, data input and output
Program and interrupt processing.

. Using data variables in shell programming can make program variables more universal, as shown in backup. sh above:
Cd $ WORKDIR
Ls * | cpio-o>/dev/rmt/0 h

Annotations in. Shell programming start #
. Perform numeric operations on shell variables and use the expr command
Expr integer operator integer
Operator is +-*/%, but escape characters must be used for *, for example:
$ Expr 4*5
20
$ Int = 'expr 5 + 7'
$ Echo $ int
12

(3) pass Shell programming parameters through command line parameters and interactive input variables (read)

Restoreall. sh restores the backup tape of the backup. sh program.
$ Cat> restoreall. sh
Cd $ WORKDIR
Cpio-I/dev/rmt/0 h
Rm-rf *

The improvements are as follows:

# When a pipeline command is used, the return code of the management command is the return code of the last command.
If ls-a | cpio-o>/dev/rmt/0 h
Then
Rm-rf *
Fi

. If-then-else statement
If command_1
Then
Command_2
Else
Command_3
Fi

Tip: Because shell does not process any extra spaces in the command, a good programmer will use this feature
Sex
Use a uniform indent format for your program to enhance the readability of your program.

. Use the test command for conditional Testing
Format: test conditions

Test is used in the following four cases: a. character comparison B. Comparison of Two integer values
C. file operations, such as whether the file exists and the file status.
D. logical operation, which can be used together with other conditions.

A. Test character data: shell variables are generally used as character variables under the Ministry of Civil Affairs.
Str1 = str2 the two are long, the same
Str1! = Str2 is different
-N string is not empty (the length is not zero)
-Z string is null
String is not empty

Example:
$ Str1 = abcd # quotation marks are required when spaces are contained.
$ Test $ str1 = abcd
$ Echo $?
0
$ Str1 = "abcd"
$ Test $ str1 = abcd
$ Echo $?
1
Note: It is best to enclose variables in quotation marks when using test to process variables containing spaces. Otherwise, errors may occur.
Result,
Because shell removes unnecessary spaces when processing commands, and enclose them with quotation marks to prevent
Shell removes these spaces.
Example:
$ Str1 = ""
$ Test $ str1
$ Echo $?
1
$ Test "$ str1"
$ Echo $?
0
$ Test-n $ str1
Test: argument expected
$ Test-n "$ str1"
$ Echo $?
0
$

B. Integer test: test is the same as expr. You can convert a variable of 'distinct' type to an integer.
While test performs logical operations.

Expression description
---------------------------------------
Int1-eq int2 is equal?
Int1-ne int2?
Int1-gt int2 int1> int2?
Int1-ge int2 int1 >=int2?
Int1-lt int2 int1 empty
$ Test-r empty
$ Echo $?
0
$ Test-s empty
1
$ Test! -S empty
$ Echo $?
0
E. logical operation of test conditions
-A And
-O Or

Example: $ test-r empty-a-s empty
$ Echo $?
1
F. Standard Method for Testing
The test command plays an important role in shell programming.
Same
For ease of reading and organization, Bourne Shell uses another method when using test: Use square brackets
Whole
Test includes:

$ Int1 = 4
$ [$ Int1-gt 2]
$ Echo $?
0

For example, rewrite the unload program and test it using test.
#! /Bin/sh
# Unload-program to backup and remove files
# Syntax: unload directory

# Check arguments
If [$ #-ne 1]
Then
Echo "usage: $0 directory"
Exit 1
Fi

# Check for valid directory name
If [! -D "$1"]
Then
Echo "$1 is not a directory"
Exit 2
Fi

Cd $1

Ls-a | cpio-o>/dev/rmt/0 h

If [$? -Eq 0]
Then
Rm-rf *
Else
Echo "A problem has occured in creating backup"
Echo "The directory will not be ereased"
Echo "Please check the backup device"
Exit 3
Fi
# End of unload

In the preceding example, exit appears. exit has two functions: stop execution of other commands in the program, and stop execution of other commands.
Yes
Set the exit status of the program

G. if nesting and elif Structure
If command
Then
Command
Else
If command
Then
Command
Else
If command
Then
Command
Fi
Fi
Fi

Improvement: Use the elif Structure
If command
Then
Command
Elif command
Then
Command
Elif command
Then
Command
Fi

The elif structure is similar to the if structure, but the structure is clearer, and the execution results are identical.
--
Bourne Shell and Shell programming (2)
H. Interactive reading data from the keyboard
Use the read Statement in the following format:

Read var1 var2... varn

Read will not replace variables, but will delete unnecessary spaces until the first line break (Press ENTER) is encountered ),
The input values are assigned to the corresponding variables in sequence.

Example:
$ Read var1 var2 var3
Hello my friends
$ Echo $ var1 $ var2 $ var3
Hello my friends
$ Echo $ var1
Hello
$ Read var1 var2 var3
Hello my dear friends
$ Echo $ var3
Dear friends while loop:
Format:
While command
Do
Command
Command
Command
...
Done

Example: Calculate the square of 1 to 5
#! /Bin/sh
#
# Filename: square. sh
Int = 1

While [$ int-le 5]
Do
Sq = 'expr $ int * $ int'
Echo $ sq
Int = 'expr $ int + 1'
Done
Echo "Job completed"

$ Sh square. sh
1
4
9
16
25
Job completed

Until cycle structure:
Format:
Until command
Do
Command
Command
....
Command
Done

Example: Calculate the square of 1-5 using the until Structure
#! /Bin/sh

Int = 1

Until [$ int-gt 5]
Do
Sq = 'expr $ int * $ int'
Echo $ sq
Int = 'expr $ int + 1'
Done
Echo "Job completed"

Use shift to process parameters with an indefinite length
In the above example, we always assume that the command line parameter is unique or the number is fixed, or use $ *
Ling
The row parameters are passed to the shell script for processing. The number of parameters is not fixed and you want
Quantity
The shift command is required for separate processing. Shift can be used to move the location parameters of the command line in sequence
,
That is, $2-> $1, $3-> $2. The first position parameter $1 before the shift will not exist after the shift.

Example:

#! /Bin/sh
#
# Filename: shifter

Until [$ #-eq 0]
Do
Echo "Argument is $1 and 'expr $#-1 'argument (s) remain"
Shift
Done


$ Shifter 1 2 3 4
Argument is 1 and 3 argument (s) remain
Argument is 2 and 2 argument (s) remain
Argument is 3 and 1 argument (s) remain
Argument is 4 and 0 argument (s) remain
$

When shift is used, every shift is performed, $ # Minus 1. With this feature, you can use the until loop
In the following example, a shell script is used to calculate the sum of integers:

#! /Bin/sh
# Sumints-a program to sum a series of integers
#

If [$ #-eq 0]
Then
Echo "Usage: sumints integer list"
Exit 1
Fi

Sum = 0

Until [$ #-eq 0]
Do
Sum = 'expr $ sum + $1'
Shift
Done
Echo $ sum


$ Sh sumints 324 34 34 12 34
438
$

Another reason for shift is that the location parameter variable of the Bourne Shell is $1 ~ $9, so the location is changed
Quantity
You can only access the first nine parameters. However, this does not mean that a maximum of nine parameters can be entered on the command line. If you want
Access
Shift is required for parameters after the first nine parameters.

In addition, you can add an integer after shift to perform multiple shifts at a time, for example:

Shift 3


. For Loop
Format:
For var in arg1 arg2... argn
Do
Command
....
Command
Done

Example:
$ For letter in a B c d e; do echo $ letter; done
A
B
C
D
E

Operations on all files in the current directory:
$ For I in *
Do
If [-f $ I]
Then
Echo "$ I is a file"
Elif [-d $ I]
Echo "$ I is a directory"
Fi
Done

Calculate the sum of all integers on the command line:
#! /Bin/sh

Sum = 0

For INT in $ *
Do
Sum = 'expr $ sum + $ int'
Done

Echo $ sum


Exit from the loop: break and continue commands
Break immediately exits the loop
Continue ignores other commands in this loop and continues the next loop

In shell programming, we sometimes use the infinite loop technique, that is, this loop is always executed.
Touch
To the break or continue command. This Infinite Loop usually starts with the true or false command. UNIX
In the system, "true" always returns 0, while "false" returns a non-zero value. As follows:

# The loop ends until the break program is executed or the user is forcibly interrupted.
While true
Do
Command
....
Command
Done

The loop shown above can also use until false, as shown below:

Until false
Do
Command
....
Command
Done

The following shell script uses the regular expressions in the continue, break, and case statements.
Method:

#! /Bin/sh
# Interactive program to restore, backup, or unload
# A directory

Echo "Welcome to the menu driven Archive program"

While true
Do
# Display a Menu
Echo
Echo "Make a Choice from the Menu below"
Echo _
Echo "1 Restore Archive"
Echo "2 Backup directory"
Echo "3 Unload directory"
Echo "4 Quit"
Echo

# Read the user's selection
Echo-n "Enter Choice :"

Read CHOICE

Case $ CHOICE in
[1-3]) echo
# Read and validate the name of the directory

Echo-n "What directory do you want? "
Read WORKDIR

If [! -D "$ WORKDIR"]
Then
Echo "Sorry, $ WORKDIR is not a directory"
Continue
Fi

# Make the directory the current working directory
Cd $ WORKDIR ;;

4):; #: the statement is empty and no action is executed.
*) Echo "Sorry, $ CHOICE is not a valid choice"
Continue
Esac

Case "$ CHOICE" in
1) echo "Restoring ..."
Cpio-I/dev/rmt/0 h ;;

3) echo "Unloading ..."
Ls | cpio-o>/dev/rmt/0 h ;;

4) echo "Quitting"
Break ;;
Esac

# Check for cpio errors

If [$? -Ne 0]
Then
Echo "A problem has occurred during the process"
If [$ CHOICE = 3]
Then
Echo "The directory will not be erased"
Fi

Echo "Please check the device and try again"
Continue
Else
If [$ CHOICE = 3]
Then
Rm *
Fi
Fi
Done


(6) Structured Programming: defining functions
Like other advanced languages, shell also provides function functions. A function is also called a subprocess (subroutine)
,
The definition format is as follows:

Funcname ()
{
Command
...
Command; # semicolon
}

After defining a function, you can call the function in shell. Using the function definition, you can call a complex program.
Minute
As follows:

# Start program

Setup ()
{Command list ;}

Do_data ()
{Command list ;}

Cleanup ()
{Command list ;}

Errors ()
{Command list ;}

Setup
Do_data
Cleanup
# End program

TIPS:
It is best to use a meaningful name when naming a function, that is, the function name can accurately describe the function
Complete
.
To facilitate program maintenance, try to use annotations


Another benefit of using a function is that the same command sequence (function) can be executed in different places in a program ),
As follows:

Iscontinue ()
{
While true
Do
Echo-n "Continue? (Y/N )"
Read ANSWER

Case $ ANSWER in
[Yy]) return 0; <
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.