Bourne shell and shell programming (1)

Source: Internet
Author: User
Bourne shell

Introduction: Bourne shell basics and many other useful features, shell programming and organization.

Main content:
Basic Introduction to. Shell, environment, options, and special characters
. Shell variables User-Defined variables, environment variables, location variables (shell parameters)
. Shell Script Programming
Conditional testing, loop and repetitive control
. Shell Customization

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
'Command' command replacement, such as filename = 'basename/usr/local/bin/tcsh'
> 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/hbwork/bin

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

Ls> filelist
Ls> filelist
Wc-l <filelist
Wc-l filelist
Sleep 5; echo 5 seconds reaches; ls-l
Ps ax | egrep inetd
Find/-name core-exec rm {}/;&
Filename = 'date "+ % Y % m % d" '. Log

2. Shell variable
Variable: represents the symbols of some values, such as $ home, CD command to find $ home, can be used in computer languages
Perform multiple operations and control.

The Bourne shell has the following four variables:
. User-Defined variables
. Location variable is a shell script Parameter
. Pre-Defined variables (Special variables)
. Environment variables (refer to the shell customization Section)
(1) User-Defined variables (Data Storage)
$ COUNT = 1
$ Name = "He binwu"

Tip: because most Unix commands use lower-case characters, full-case variables are usually used in shell programming,
Of course this is not mandatory, but using uppercase characters can easily identify variables in programming.

Call a variable: add $
$ Echo $ home
/Home/hbwork
$ Week = Satur
$ Echo today is $ weekday
Today is
$ Echo today is $ {week} day
Today is Saturday

Assign a value to a shell variable from right to left (assign a value to Linux Shell/Bash from left to right !)
$ X = $ Y = y
$ Echo $ x
Y
$ Z = z y = $ Z
$ Echo $ y

$

Use the unset command to delete the value assignment of a Variable
$ Z = Hello
$ Echo $ Z
Hello
$ Unset Z
$ Echo $ Z

$

Conditional command replacement
In the Bourne shell, variable replacement can be executed under specific conditions, that is, conditional environment variable replacement.
This type of variable replacement is always enclosed in braces.

. Set the default value of the Variable
The value is null before the variable is assigned a value. The Bourne shell allows you to set default values for variables in the following format:
$ {Variable:-defaultvalue}
Example:
$ Echo Hello $ uname
Hello
$ Echo Hello $ {uname:-there}
Hello there
$ Echo $ uname # The variable value has not changed.

$ Uname = hbwork
$ Echo Hello $ {uname:-there}
Hello hbwork
$
. Another case: Change the variable value in the following format:
$ {Variable: = value}

Example:
$ Echo Hello $ UNAME
Hello
$ Echo Hello $ {UNAME: = there}
Hello there
$ Echo $ UNAME # The variable value has not changed.
There
$
Replace variables with commands
$ USERDIR =$ {$ MYDIR:-'pwd '}

. Replace $ {variable: + value} when the variable has been assigned a value}
. Conditional Variable replacement with error check
$ {Variable :? Value}
Example:
$ UNAME =
$ Echo $ {UNAME :? "UNAME has not been set "}
UNAME: UNAME has not been set
$ Echo $ {UNAME :?}
UNAME: parameter null or not set

(2) location variable (Shell parameter)
In shell script, the location parameter can be represented by $1 .. $9. $0 indicates that the content is usually the name of the file of the currently executed program.
. Prevent the variable value from being replaced by readonly variable
. Use the export command to output the variable so that the variable is available to the sub-shell. When the shell executes the program, the shell
A new environment will be set for it to execute, which is called subshell. In the Bourne Shell, the variable is usually
It is considered a local variable, that is, the variable is not recognized outside the shell environment except the value assignment. Enable
Use export to use subshell.

For example, for the export Operation of the variable PS1, the shell prompt will change.
$ PS1 = 'hostname' $
Peony $ sh
$ Echo $ PS1
$ <-Output result
$ Exit
Peony $ export PS1
Peony $ sh
Peony $ echo $ PS1
Peony $ <-output result
Peony $

3. Shell Script Programming
Objective: To use the most common tools provided by UNIX to complete the powerful functions of the required complex tasks.

(1) simplest Shell programming
$ Ls-R/| grep myname | more

Daily Data Backup:
$ Cd/usr/yourname; ls * | cpio-o>/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 character/is 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
^ D
Restore1.sh: only one file can be restored.
# Restore1 -- program to restore a single file
Cd $ WORKDIR
Cpio-I $ I </dev/rmt/0 h

$ Restore1 file1

Restore multiple files:
# Restoreany -- program to restore a single file
Cd $ WORKDIR
Cpio-I $ * </dev/rmt/0 h

$ Restoreany file1 file2 file3

(4) condition judgment
. If-then Statement, in the following format:
If command_1
Then
Command_2
Command_3
Fi
Command_4

The command return code $? Is Used in the if-then statement ?, That is, command_2 and
Command_3, while command_4 is always executed.

Example program unload: Delete the original file when the backup is successful with an error check

Cd $1
# Failed backups are not considered!
Ls-A | cpio-o>/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.
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 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: When using test to process variables containing spaces, it is best to enclose the variables in quotation marks. Otherwise, an error will occur,
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 <int2?
Int1-Le int2 int1 <= int2?

Example:
$ Int1 = 1234
$ Int2 = 01234
$ Test $ int1-EQ $ int2
$ Echo $?
0

C. File test: Check the file status, such as the existence and read/write permissions.

-R filename: Do users have read permission on filename?
-W filename: Do users have write permission on filename?
-Does the X filename user have the executable permission on the file filename?
-F filename: Is the file filename a common file?
-D is the filename of the filename file a directory?
-C filename file: Is filename a character device file?
-B. Is the filename file a block device file?
-S filename file is not zero?
-T fnumb is a terminal device related to the file descriptor fnumb (default value: 1?

D. Negative test conditions. Use it!
Example:
$ Cat/dev/null> 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
Because the test command plays an important role in shell programming, in order to make the shell be the same as other programming languages
For ease of reading and organization, Bourne Shell uses another method when using test: Use square brackets
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 has two functions: one is to stop the execution of other commands in the program, and the other is
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.

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.