Getting Started with Shell programming

Source: Internet
Author: User
Tags control characters first string time and date

Shell background

The first important shell was the Bourne shell (so named to commemorate the Shell's inventor Steven Bourne), when the first popular Unix version 7 was released in 1979, and began to use

Bourne Shell. Bourne Shell's main file name is sh, so later people will use SH as the main identifying name of the Bourne shell. Although there are many kinds of shells on Unix, Bourne shell

's status has not changed so far. SH is still used as an important management tool in many Unix systems.

The first widely used shell variant is the C shell. C shell is mainly attached to the BSD version of the Unix system. Its author is Bill Joy of the University of Berkeley. C shell is mainly because of its syntax and C language

is similar, hence the name. This makes it easy for Unix-system programmers to feel quite local when learning C shell. These two types form the shell's two major mainstream, and later variant shells mostly grab the advantages of these two shells.

Like Korn, tcsh and bash.

The Bash shell is one of the most important software tools in the GNU program and is the standard shell in the GNU operating system. Bash is compatible with SH, so many early-developed Bourne shells can continue to bash

In the operation. Now we've installed Redhat Linux to use Bash completely. (/bin/sh-/bin/bash)


What is a shell?

In computer science, the shell is commonly known as a shell (used to differentiate itself from the kernel) and refers to the "user Interface" software (command parser). It is similar to DOS command and later cmd.exe. It receives user commands,

Then call the appropriate application. It is also a programming language. As a command language, it interactively interprets and executes commands entered by the user or automatically interprets and executes a set of predetermined commands; as a programming

Language, which defines variables and parameters, and provides many control structures in high-level languages, including loops and branches.

Basically there are two main types of shells:

One: Graphical interface shell (graphical User Interface shell is GUI shell)

II: Command-line shell (CLI shell, Interface shell)

The common shell commands are:
Cat filename Output file content to basic output (screen or add >filename to another file)
CB Format Source Code
chmod//change mode, change the permissions of the file
CP Copy
Date Current time and date
echo $ABC After the variable is assigned, simply precede the variable with a $ reference.
Lint grammar checker
LS dir
Mans Help
More Type
Du view disk space status
PS View Current process status
Who your user name and terminal type
Define variable NAME=ABC? (Bash/pdksh) | | Set name = ABC (TCSH)
mkdir Creating a Directory
RmDir Deleting a directory
CD Entry Directory
RM Delete File
More Display files
ECHO Displays the specified text
MV Change file name
PWD Display directory path command

The basic structure of the shell program:

Use the editor to create a hello.sh that reads as follows:

#! /bin/bash
#hello
echo ' Hello World '

Here's what you need to explain:
1. Develop good habits, shell files with ". Sh" as a suffix (no. sh suffix files can also be run)
2. Note Start with "#"
3. The first line of the text must be written in #!/bin/bash (#! is where you use the path of the shell)
4. Edit the text to let it run, use the "chmod +x hello.sh" command in the terminal (Add executable permission)
5. Run the program: Use the "./hello.sh" command in the terminal


Three types of variables in the shell: System variables, environment variables, user-defined variables

User-defined variables: User-declared variables in programming, not described here

System variables:
The common system variables are:

The name of the current program
$n the nth parameter of the current program, n=1,2,... 9
$* all parameters of the current program (excluding the program itself)
$# the number of parameters for the current program (excluding the program itself)
$$ PID of current program
[Email protected] and $ #相同, but use quotation marks and return each parameter in quotation marks
$-shows the current options used by the shell, same as the SET command function
$! Perform the PID of the previous instruction (not as if?)
$? Executes the return value of the previous instruction

Environment variables:
The shell environment variable is a parameter that all shell programs will accept. When the shell program runs, it receives a set of variables that are environment variables

Use the "Export" command in the terminal to view the list of environment variables for the system

1. Common environment variables.
Path: System path.
Home: Current User home Directory
Histsize: Saves the number of records recorded by the history command.
LOGNAME: The current user login name.
Hoatname: Host name, if the application is to use the hostname, it is generally obtained from this environment variable.
Shell: What kind of shell is used by the current user.
Lang/languge: and language-related environment variables, users in multiple languages can modify this environment variable.
Mail: The current user's message store directory.

2. How to set environment variables
Etho: Displays the specified environment variable.
Export: Setting a new environment variable
ENV: Displays all environment variables.
Set: Displays all locally defined shell variables.
unset: Clears environment variables.

3. Several examples
①. Display Environment Variables Home
$ echo $HOME
/home/leon

② setting a new environment variable Hello
$ export hello= "hello!"
$ echo $HELLO
Hello!

③ Display all environment variables using the ENV command
$ env
hostname=redbooks.safe.org
Pvm_rsh=/usr/bin/rsh
Shell=/bin/bash
Term=xterm
histsize=1000
...

④ using the SET command to display all locally defined shell variables
$ set
Bash=/bin/bash
bash_versinfo= ([0]= "2" [1]= "05b" [2]= "0" [3]= "1" [4]= "Release" [5]= "I386-redhat-linux-gnu")
Bash_version= ' 2.05b.0 (1)-release '
Colors=/etc/dir_colors.xterm
Columns=80
Dirstack= ()
display=:0.0
...

⑤ using the unset command to clear environment variables
Set sets the value of an environment variable. Clear the value of the environment variable with the unset command. If no value is specified, the value of the variable is set to NULL. Examples are as follows:
$ export test= "TEST ..." #增加一个环境变量TEST
$ env|grep Test #此命令有输入, proving that the environment variable test already exists
Test=test ...
$ unset $TEST #删除环境变量TEST
$ env|grep Test #此命令没有输出, proving that the environment variable test already exists

⑥. To set a read-only variable using the readonly command
If the readonly command is used, the variable cannot be modified or erased. Examples are as follows:
$ export test= "TEST ..." #增加一个环境变量TEST
$ readonly TEST #将环境变量TEST设为只读
$ unset TEST #会发现此变量不能被删除
-bash:unset:test:cannot unset:readonly Variable
$ test= "New" #会发现此也变量不能被修改
-bash:test:readonly variable
Settings for environment variables are located in the/etc/profile file
If you need to add a new environment variable, you can include a subordinate row
Export path= $path:/PATH1:/PATH2:/PAHTN

In instance ②, you use the Export command to define an environment variable that is valid only in all currently running processes and is not saved to the system file. These variables cannot be accessed after the system restarts,

Therefore, these environment variables can be configured again in the system configuration. The system configuration file for the environment variable is/etc/profile. The configuration environment variable steps are as follows:

1. Use the "gedit/etc/profile" command in the Terminal (Edit profile)

2. Add the following code at the end of the file, adding two environment variables
Export A1=hello
Export a2=123
3. Save the file, restart the computer, the system will produce the above settings of the two environment variables


operator of the Shell

=str=hello
+ Plus
-Minus
* Multiply
/except
* * Power operation
% modulo operation (redundancy)
+ = Plus equals (adds a second variable on its own basis)
-= minus equals
*= multiply equals
/= except equal to
%= to touch the assignment (the first variable takes a modulo operation on the second variable, assigns it to the first variable)

Question: Echo 1+2
The shell does not output the result 3, but the output 1+2

WORKAROUND: Change the order of operations in three different ways
① use expr to change the order of operations: use echo ' expr 1+2 ' output ' 1+2 ', note ' ' ' is not a single quote, it is the symbol above the ' tab ' key

② uses let to indicate mathematical operations: The result is assigned to B, the Operation command is B=let 1+2, and then the echo $b to output, if there is no let or output 1+2

③ using $[] to represent mathematical operations: using echo $[1+2], output 3

Use positional variables to implement the operation:

Edit the operation.sh file with the following content:
#!/bin/bash
#operation. Sh
S=0
s= ' Expr $1**s2 '
Echo $s

After attaching execute permissions to the file using "chmod +x operation.sh" in the terminal, using the "./operation.sh 2 4" command, the output of the operation is 16 (2 of 4).

Description: A positional variable is a parameter passed in by the shell program at run time. These parameters can be called in the program in the form of variables. These parameters are stored in the nine variable names of 1~9 ($0,$1......$9) and are called positional variables by image.


Input and output

Use the Read command to enter:
1. "Read A" corresponds to the scanf () function in the C language
2. You can also enter multiple values for "read a B" and assign values to A and B, respectively.

Using the Echo output:
1. Echo $str # Outputs the result to the terminal
2. Echo $str >file# Output The result to a file file, and if not, create a new one and overwrite the file contents
3. Echo $str >>file# Append the result to the file
4. Format controls the use of characters \c, \ t, and \ n:
\c: No Line break
\ t: Jump, equivalent to Tab key
\ n: Line break
Note: When using format control characters, you must add the-e option, such as ECHO-E "hello\tbeijing", to Output "hellobeijing"

5. The escape character in the shell is the backslash "\"


Use of Shell test statements

File status test:

File status test refers to the file's permissions, have, attributes, types and other content to judge. In contrast to other languages, the test result of the tests command returns 0 to indicate that the test was successful. Returning 1 indicates that the test failed.

The main parameters are
-D test is a directory
-F test is a file
-e test whether the directory or file exists
-R tests whether the current user has Read rights
-W tests whether the current user has write permissions
-X tests whether the current user has Execute permissions
Instance:
1. Test whether the file is a directory: test-d/file
2. Test whether the file A.txt in the current directory is executable: Test-x a.txt


Numerical test:

Refers to the comparison of the size or equality of two values

Syntax: Test first operand numeric comparer second operand
Or: [Number of first operand numeric comparer second operand]
Note: There is an interval between [] and the operand

The numeric comparison characters are:
-eq equal
-ne not the same
-le less than or equal to
-ge greater than or equal to
-GT Greater than
-lt less than

Instance:
1. Test whether 3 and 5 are equal: Test 3-eq 5 or [3-eq 5]
2. Test 10 is less than 12:test 10-lt 12 or [10-lt 12]


String test:

This is commonly used to test whether a user's input conforms to a program's requirements by comparing the equality of two strings, or by determining whether a string is empty.

Common methods:
Test string comparison string
Test string 1 string comparison string 2
[string comparison string 1]
[String 1 string Comparer string 2]

String comparer:
= The first string is equal to the second string
! = The first string and the second string are not equal
-Z Checks if the string is empty
-N checks whether the string is non-null

Example: Test if variable A is equal to variable B: Test $A = $B

Logic test:

-A logic and
-O Logic or
! Logical No

Example: Test file a.txt is writable: [-W a.txt-a-X. txt]


Process Control Structure:

If statement:
Edit a test.sh file with the following content:

#!/bin/sh
echo "Is it morning?" Please answer yes or no "
Read time
If ["$time" = "yes"]; Then echo "Good Morning"
elif ["$time" = "no"]; Then echo "Good Afternoon"
else echo "Sorry, $time not recquired,enter yes or no"
Exit 1
Fi
Exit 0

Description: The IF structure must be finished with fi;
Elif equivalent to else if is not a syntax error

For statement:

Grammar:
For variable name in list
Do
Command 1
Command 2 ...
Done

Example 1:
#!/bin/sh
for Foo in 1 2 3
Do
Echo $foo
Done
Exit 0

Output: 1
2
3

Example 2:
#! /bin/sh
For STR
Do
Echo-e "$str \c"
Done

When the for statement omits the in keyword, the parameters of the input command are accepted as a set of cyclic variables, test.sh a B C is entered in the terminal, and the program input results are: ABC

Example 3:
A For loop with wildcard extensions
The For loop is often used with the shell's wildcard extension of file names. That is, add a wildcard character to the value of the string, and the shell fills all the values when the program executes. For example

#!/bin/sh
For file in $ (ls *.sh);
Do
LPR $file
Done
Exit 0

This example prints the. sh files in the current directory.

Example 4:
99 Multiplication Table
#!/bin/sh
For I in 1 2 3 4 5 6 7 8 9
Do
For j in 1 2 3 45 6 7 8 9
Do
If [$j-le $i] #比较i和j的大小关系实现排列
Then Echo-e "$j \c"
Echo-e "*\c"
Echo-e "$i \c"
Echo-e "=\c"
ECHO-E "$[$i * $j] \c"
Fi
Done
echo ""
Done


While statement:

Instance
#!/bin/sh
Foo=1
While [$foo-le 3]
Do
echo "Now Foo is $foo"
foo=$ (($foo + 1))
Done

Output: now Foo is 1
Now Foo is 2
Now Foo is 3

Until statement:

Grammar:
Until conditions
Do
Command 1
......
Done

Instance

#!/bin/sh
I=1
Until [$i-GT 3]
Do
Echo-e "$i \c"
i=$[$i +1]
Done

Output Result: 123

Getting Started with Shell programming

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.