Shell script Basics

Source: Internet
Author: User
Tags echo name
Common shell: -------------- from "laruence's Linux private dish"

In the early UNIX era, there were many developers, so shell had many versions based on the developer's differences, such

Frequently heard Bourne shell (SH ),
C shell,
Commonly used K shell in business,
There are also tcsh and so on. Each shell has its own characteristics.

AsLinuxThis version is called "Bourne again shell (BASH )』,
This shell isEnhanced version of Bourne shellIt is developed based on the GNU architecture!

Before introducing the advantages of shell, let's talk about the simple history of shell: the first popular shell was developed by Steven Bourne. to commemorate it, it is called the Bourne shell, or directly referred to as sh! Later, another widely used shell was designed by Bill Joy of the University of Berkeley to be attached to the shell in the bsd unix system. The shell syntax is a bit similar to the C language, therefore, the name must be c shell, or CSH for short! In the academic world, Sun hosts are quite powerful, while sun is mainly one of the branches of BSD. Therefore, C shell is also one of the most important and widely spread shells (because there are too manyProgramThe designer uses the C language !)!

========================================================== ======================================

Shell programming Overview------------ Source:

InIn dos, you may be engaged in some routine overwriting work. At this time, you will write these overwriting commands into batch files, you only need to execute this batch of files to execute these commands. You will ask if there is batch processing in Unix. The answer is yes. In UNIX, not only is it like DOS batch processing, but it is more powerful and complex than dos. It is already comparable to general high-level languages. In UNIX, it is not called a batch file, but a shell script.

Generally, shell scripts have the same status as other executable files (or commands), except that shell scripts are stored as text files rather than binary files. When executing a shell script, a program must convert its content into a single command for execution, and this program is actually a shell, this is why we call it shell script (or script later ). Different shell scripts are basically different, so we cannot use B shell to execute scripts written to a shell. In UNIX, we usually use the Bourne shell and C shell, so this course introduces the writing of these two types of scripts.

Set the text file to an executable shell script

If we have already written a script, how can we set it to an executable file? Because a script is an executable file, the access permission must be set to executable. You can use the following command to change the access permission:
Chmod U + x filename can only be executed by yourself, but cannot be executed by others
Chmod ug + x filename can be executed only by yourself and the same group, but not by others.
Chmod + x filename can be executed by all users

But how do we specify the shell to explain the written script? The following describes how to specify the parameters:
1. If the first non-blank character of the script is not "#", it uses the Bourne shell.
2. If the first non-blank character of the script is "#", but not "#! ", It will use C shell.
3. If the script uses "#! ", Then "#! "What is written in the back is the shell used, and the whole path name should be pointed out.

We recommend that you specify the shell in the third way to ensure that what is executed is what you want. The path name of the Bourne shell is/bin/sh, while that of the C shell is/bin/CSH.

1. Use the Bourne shell
Certificate ---------- certificate ---------- Certificate
│ Echo enter filename │ #! /Bin/sh │
│. │ Or │. │
│. │. │
│. │. │
Certificate ---------- certificate ---------- Certificate

2. Use C Shell
Certificate ---------- certificate ---------- Certificate
│ # C shell script │ #! /Bin/CSH │
│. │. │
│. │. │
│. │. │
Certificate ---------- certificate ---------- Certificate

3. Use/etc/perl
Certificate ---------- Certificate
│ #! /Etc/perl │
│. │
│. │
│. │
Certificate ---------- Certificate

In addition to specifying the shell used in the script, you can also forcibly specify it in the Command column. For example, if you want to use C shell to execute a script, you can run the following command:
CSH filename

In this case, the access to the script is not necessarily executable, and the shell specified in the script is invalid. The details will be discussed later.

□Basic structure and concept of script

The script is a unit of action. The script we write will be divided into one row for execution. Each line can be commands, annotations, or process control commands. If a row has not been completed, you can add "\" at the end of the row. At this time, the content of the next row will be received at the end of the row and become the same row, as shown below:

Certificate ----------- Certificate
│ Echo the message is \ │
│ Too long so we have \ │
│ To split it into \ │
│ Several lines │
Certificate ----------- Certificate

When "#" appears in the script, the same line of text after it is annotated, and shell will not translate it.

The method for executing a command in a script is the same as that in the Command column. You can execute the command in the foreground or background. Some environment variables need to be set when executing the command.

The Process Control of a script is no different from that of a general high-level language. It also has sub-programs like a high-level language. These make the script more powerful.

To achieve the same effect as a higher-level language, we can also set variables in the script, so that the script becomes a higher-level language.

□Bourne Shell

I. Variables

The variable type of the Bourne shell is only a string variable. Therefore, to use numeric operations, you must rely on external commands for the purpose. The variable types include:

1. User Variables

This is the most commonly used variable. We can use any string that does not contain blank characters as the variable name. The following method is used to set the variable value:
Var = string

When a variable is used, a "$" number is added before the variable name.

Certificate ------- Certificate
│ Name = Tom │
│ Echo name │
│ Echo $ name │
Certificate ------- Certificate
The result is as follows:

2. System variables (environment variables)

Similar to a user variable, except that the variable passes its value to the command it executes. To set a user variable to a system variable, add:
Export VaR

Certificate ------- Certificate
│ Name = Tom │
│ Export name │
Certificate ------- Certificate

The following are the system variables that have been set when the user enters the system:
$ Home user's own directory
$ Path: the directory to be searched during Command Execution
$ TZ Time Zone
$ Mailcheck the number of seconds to check whether a new letter exists
$ PS1 prompt number in the Command Column
$ PS2 indicates the prompt number when shell requests to re-input when the command has not been completed
$ Manpath man command search path

3. Read-Only user variable

Similar to user variables, but these variables cannot be changed. To set the user variable to read-only, you only need to add:
Readonly VaR

If only readonly is used, all read-only variables are listed. Another point is that the system variable cannot be set to read-only.

Certificate ------- Certificate
│ Name = Tom │
│ Readonly name │
│ Echo $ name │
│ Name = John │
│ Readonly │
Certificate ------- Certificate

The result is as follows:
Name: Is read only
Readonly name
Readonly ......

4. Special Variables

Some variables are set at the beginning of script execution and are not modified, but we do not call them a read-only system variable, it is called a special variable (some books will call it a read-only system variable), because these variables are generated when the script is executed, moreover, users cannot set general system variables to read-only. The following are some special variables:
$0 name of the script file
$ N the nth command line parameter of the script, n = 1 .. 9
$ * All command line parameters constitute a whole, as a "word"
$ # Number of command line parameters
$ PID of the Shell Process
$! PID of the background process last started by the Shell Process
$? Return code of the last executed command
$ @ Think of all command line parameters as multiple "Words"

When you run this program with more than 9 parameters, we can use the shift command to move the parameters forward to one cell, so that we can use 10th parameters. In addition, we can use the set command to change $ N and $ *. The method is as follows:
Set string

In this case, the value of $ * is a string, which is put into $ N after decomposition. If there are no parameters at the end of the SET command, all the preset variables and their values are listed.

File Name: ex1 parameter: this is a test

Certificate ----------- Certificate
│ Echo filename: $0 │
│ Echo arguments: $ * │
│ Echo No. of argS.: $ # │
│ Echo 2nd Arg.: $2 │
│ Shift │
│ Echo No. of argS.: $ # │
│ Echo 2nd Arg.: $2 │
│ Set hello, everyone │
│ Echo arguments: $ * │
│ Echo 2nd Arg.: $2 │
Certificate ----------- Certificate
The result is as follows:
Filename: ex1
Arguments: this is a test
No. of argS.: 4
2nd Arg.: Is
No. of argS.: 3
2nd Arg.:
Arguments: Hello, everyone
2nd Arg.: everyone

It is worth mentioning that when you want to input a variable value from the keyboard, you can use the following command:
Read var1 var2 .....

In this case, read will distribute a word to a variable. If more words are input than variables, the last variable regards the remaining words as its values. If less words are entered than the variable, the variable is set to a null string. To handle numeric operations, we can use the expr command. Its Parameters and output are listed in Appendix.

Ii. execute commands

There are five methods in the Bourne shell to execute a command, and the results of these five methods are somewhat different.

1. directly run the command
This method is the same as running a command directly in the Command column.

2. Use the sh command
Sh command
This file must be a script of the Bourne shell, but it is not necessarily executable. In addition, it is the same as running commands directly.

3. Use the "." command
. Command

In this case, it is similar to the sh command, except that it does not generate a new process like sh. On the contrary, it will complete the work in the original process.

4. Run the exec command
EXEC command
In this case, the script will be replaced by the executed command. After the command is executed, the script ends.

5. Use commands to replace
This is a very useful method. If you want to make the output of a command a parameter of another command, you must use this method. The command is listed between two "'" signs, and shell will replace the command and the two "'" symbols with the output result after the command is executed.

STR = 'current directory is ''pwd'
Echo $ Str
The result is as follows:
Current directory is/users/CC/mgtsai
This means that the command PWD outputs "/users/CC/mgtsai", and then the entire string replaces the original 'pwd' to set the STR variable, therefore, the STR variable contains the output of the PWD command.

Number = 'expr $ number + 1'
This is the method for performing numerical operations on the preceding abstract. Basically, the expr command only resolves the formula and then outputs it to the standard output. If you want to set a variable to its value, you must replace it with a command. In this example, the value of the number variable is added to 1 and then stored back to the number variable.

3. Process Control

Before introducing process control, let's take a look at the test command. The parameter of the test command is conditional. If the condition is true, a non-zero value is returned, and if the condition is false, zero is returned. In all process control, the test command must be used to determine the authenticity. The usage of the test command is listed in Appendix B.

Test $ # = 0

If the program runs without parameters, a non-zero value is returned, indicating that the condition "$ # = 0" is true. Otherwise, zero is returned.

The following describes various process controls:

1. The if then syntax and flowchart are as follows:

│ False
If (condition) <condition>-Condition
Then │ true │
Then-commands then-commands │
FI done ---- done

Condition is a test command. The condition commands in the subsequent processes are test commands.
File Name: chkarg

Certificate ----------- Certificate
│ If (test $ #! = 0) │
│ Then │
│ Echo arg1: $1 │
│ Fi │
Certificate ----------- Certificate
$ Chkarg hello
Arg1: Hello
$ Chkarg

2. if then else syntax and flowchart are as follows:

│ False
If (condition) <condition> ----- Condition
Then │ true │
Then-commands then-commands else-Commands
Else release -------- release
Else-commands │

3. If then Elif syntax and flowchart are as follows:

│ False
If (condition1) <condition1>-Condition
Then │ true │ false
Commands1 commands1 <condition2>-Condition
Elif (condition2) │ true │
Then │ commands2 commands3
Commands2 certificate ----- snapshot ---- Snapshot
Else │


Echo 'word 1: \ C'
Read word1
Echo 'word 2: \ C'
Read word2
Echo 'word 3: \ C'
Read word3
If (test "$ word1" = "$ word2"-a "$ word2" = "$ word3 ")
Echo 'match: Words 1, 2, & 3'
Elif (test "$ word1" = "$ word2 ")
Echo 'match: Words 1 & 2'
Elif (test "$ word1" = "$ word3 ")
Echo 'match: Words 1 & 3'
Elif (test "$ word2" = "$ word3 ")
Echo 'match: Words 2 & 3'
Echo 'no Match'

4. The for in syntax and flowchart are as follows:

│ False
For VaR in Arg-List objects-<Arg-list is there anything else?> -Timeout
Do │ true │
Commands │ obtain an item from Arg-list │
Done │ put the variable VAR │

│ Commands │
Certificate ------ certificate │
Certificate ----------- certificate ----- Certificate
│ For a in xx yy zz │
│ Do │
│ Echo $ A │
│ Done │
Certificate ----------- Certificate
The result is as follows:


5. The for syntax and flowchart are as follows:

│ False
For var callback-<is there anything in the parameter?> -Timeout
Do │ true │
Commands │ obtain an item from the parameter │
Done │ put the variable VAR │

│ Commands │
Certificate ----- certificate │
File Name: lstarg certificate ----- example
Certificate ----------- certificate │
│ For a │
│ Do │
│ Echo $ A │
│ Done │
Certificate ----------- Certificate
$ Lstarg XX YY ZZ


6. The while syntax and flowchart are as follows:

│ False
While (condition) condition-<condition>-Condition
Do │ true │
Commands │ commands │
Done networks ---- Hangzhou │
Certificate ---- Snapshot

Certificate --------------- Certificate
│ Number = 0 │
│ While (test $ number-LT 10) │
│ Do │
│ Echo "$ number \ c" │
│ Number = 'expr $ number + 1' │
│ Done │
│ Echo │
Certificate --------------- Certificate
The result is as follows:

7. The until syntax and flowchart are as follows:

│ True
Until (condition) condition-<condition>-Condition
Do │ false │
Commands │ commands │
Done networks ---- Hangzhou │
Certificate ---- Snapshot

It differs from while only when while is executed when the condition is true, while until is executed when the condition is false.

8. Break and continue
The two are used in for, while, until and Other loop control. The break will jump to the done side for execution, while the continue will jump to the done for execution and continue to execute the loop.

9. The case syntax and flowchart are as follows:

│ True
Case STR in <STR = pat1> ---- commands1-Example
Pat1 = commands1; │ false true │
Pat2 = commands2; <STR = pat2> ---- commands2-Example
Pat3 = commands3; │ false true │
Esac <STR = pat3> ---- commands3-Example
│ False │
Certificate ------------ Certificate

In addition to specifying certain strings, Pat can also specify a string set, as shown below:
* Any string
? Any character
[ABC] A, B, or C
[A-N] any character from A to N
| Multiple options

hour --------------- hour
│ echo 'enter A, B, or C: \ c '│
│ read letter │
│ case $ letter in │
│ A | A = echo' you entered. '; │
│ B | B = echo' you entered B. '; │
│ c | C = echo' you entered C. '; │
│ * = echo 'not a, B, or C'; │
│ esac │

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: 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.