0 Basic Learning Shell programming

Source: Internet
Author: User
Tags echo command

One: Cause

(0) Perhaps because of a momentary impulse you start to focus on and learn shell programming, but also because the "hearsay" shell is very powerful, but also because of the charm of shell programming, but also because as a coder of the preferences, also Xu ...

(1) First to figure out why to learn the shell, learning to be purposeful----simply saying that the shell is a file containing several lines of shell or Linux commands. For a large number of commands that are written and used more than once, you can use a separate file to save it for later use.

The shell is simple, flexible, and efficient, and is especially suitable for dealing with some minor system management issues .

Shell automates management , making it easy, easy, and efficient for system administrators to work

The shell can store a number of commands or operations that are often needed, in the form of a file, every time you call, without repeating the type of command

Shell scripts are portable and can be ported flexibly in the Unix/linux system, with virtually no setup to run properly

Shell scripts make it easy to read and modify source code without having to compile and master the shell to help you troubleshoot problems such as script-induced failures

Mastering the shell is an intermediate system engineer must be required to master the shell is your system management advanced step

Mastering the shell is a stepping stone to your higher-level job interview.

(2) When does the shell script not be used?

resource-intensive tasks, especially when you need to consider efficiency (such as sorting, hashing, etc.)

Mathematical operations that need to handle large tasks, especially floating-point operations, precision operations, or complex arithmetic operations (typically handled using C + + or FORTRAN)

Complex applications with cross-platform porting requirements (typically C or Java) , when structured programming is required (requires type checking of variables, function prototypes, etc.)

For mission-critical applications that affect the overall system.   Tasks that require a high level of security, such as the need for a robust system to prevent intrusion, cracking, vandalism, and so on. A project consists of various parts of a chain of dependencies.

Require large-scale file operations or support for multidimensional arrays that require data structures such as linked lists or numbers

Need to produce or manipulate graphical interface GUI requires direct OS hardware requires I/O or socket interface

Interfaces that require the use of libraries or legacy old code private, closed-source applications (shell scripts put the code in a text file that the world can see)

If your app fits any of the above, consider a more powerful language-perhaps Perl,python,ruby, or a higher-level compiler language such as C/c++,java

Second: Knowledge Point Introduction

(1) From the beginning of script writing and execution-write with VIM can be saved as filename.sh file, before execution needs to change to executable file or sh filename.sh to execute:

1) Usually the shell script is suffixed with. Sh . When writing the shell, the first line must indicate which shell the system needs to interpret the user's shell, such as: #!/bin/sh,#!/bin/bash, #!/bin/csh,,#!/bin/tcsh, and #!/bin/ Ksh and so on. The following run.sh indicates the use of bash execution.
#!bin/bash
Ls-l
Typically, shell scripts use #!/bin/sh as the default shell program. There are two ways to execute a shell: the first is to add executable permissions to the shell script and execute it, and the second is to execute the shell script through the SH command, such as executing the run.sh script under the current directory, with the following command:
Add executable permissions directly to the shell script and execute
chmod 755 run.sh
./run.sh

2)//execute shell script via sh command

SH run.sh
Note: Why can "sh shell.sh" also run?
This is because/bin/sh is actually/bin/bash (link file), using SH shell.sh that is to tell the system, I want to directly to bash function to run shell.sh the relevant command in this file meaning, so at this time your shell.sh as long as have R permission can be run Oh! And we can also use SH parameters, such as-N and-X to check and trace shell.sh syntax is correct?
Sh-x filename.sh
This executes the script and displays the values of all the variables in the script, or it can use the parameter-N, which does not execute the script, but returns all syntax errors.

(2) Let's start with the classic "Hello World" and take a look at the simplest shell script.

sudo vim hello.sh:

#!/bin/sh
#print Hello World in the console window
A= "Hello World"
echo "Hi, ${a}s"

chmod 755 hello.sh Change to executable rwx (4,2,1)

SH hello.sh or./hello.sh

(3) Special characters in the shell

Like other programming languages, there are special characters in the shell. Common is the dollar sign ($), backslash (\), and quotation marks.

1) Dollar sign

The dollar sign represents a variable substitution, which replaces the variable with the value of the variable specified later. The backslash "\" is an escape character, and the escape character tells the shell not to treat the character that follows it specially, just as a normal character.

2) Double quotation marks (")

Characters enclosed in double quotation marks, except $, the inverted quotation mark ('), and the backslash (\) still retain their special functions, and the remaining characters are treated as ordinary characters nonspacing.
3) Single quotation mark (')
The character nonalphanumeric enclosed by single quotation marks appears as normal characters.

4) Inverted quotation mark (') tab key above the original character

The quoted string is interpreted by the shell as the command line, and at execution time, the shell executes the command and replaces the entire quotation mark with its standard output.

5) Example

The code and output for example 1 are as follows:
#echo "My current directory was ' pwd ' and logname is $LOGNAME" "double quotation marks and dollar signs keep the original function"
My current directory Is/root and LogName is root
The code and output for example 2 are as follows:
#echo "My current directory is ' pwd ' and logname are \ $LOGNAME" "Escape characters in double quotes keep the original function"
My current directory Is/root and LogName are $LOGNAME
The code and output for example 3 are as follows:
#echo ' My current directory was ' pwd ' and logname is $LOGNAME ' "The contents of the single quotation mark are unchanged"
My current directory was ' pwd ' and logname is $LOGNAME

6) variables

Shell variables are very similar to JS and Python, but one thing to note is that variables and equal signs (i.e., no spaces before and after the equals sign), such as num=10, but if [${num} eq.];then ... fi this space must be there.

(4) Comments for Shell scripts

Shell scripts, like other programming languages, have annotations as well. The comment method is to add the # sign before the comment line.
For example, the following script:
#!/bin/sh
#Filename: comment.sh
#Description: This script explains what to make a comment
echo "This script explains what to make a comment"

When you create a script, the first line of the script is often called a Shbang (#!) line. When the script starts, the UNIX kernel examines the first line of the file to determine which type of program will be executed.

The path behind the Shbang symbol (#!) is the shell location used to interpret this script. To use this feature correctly, #! Must be the first two characters in the file. If
This attribute is ignored when the file header has a space character or a blank line, and the line is interpreted as a normal comment line.

(5) See the Mystery of SH script execution again

Open a text editor, create a new file, the extension sh (sh for Shell), the extension does not affect the execution of the script, see the name is Good , if you write a shell script in PHP, the extension is good with PHP.
Enter some code:
#!/bin/bash
echo "Hello world!"
"#!" is a contract tag that tells the system what interpreter the script needs to execute , even if it uses a shell. The echo command ( preferably with $printf "" for better portability) is used to output text to the window.
Save the above code as test.sh and CD to the appropriate directory:

chmod +x./test.sh #使脚本具有执行权限
./test.sh #执行脚本

Note, be sure to write./test.sh, not test.sh. Running other binary programs is the same, the direct write Test.sh,linux system will go to the path to find whether it is called Test.
SH, and only/bin,/sbin,/usr/bin,/usr/sbin, etc. in the path, your current directory is usually not in the path, so written test.sh will not find the command, to use./test.sh tells the system that it is looking in the current directory.
To run the bash script this way, the first line must be written so that the system can find the correct interpreter.
The "system" here is actually the shell application (imagine Windows Explorer), but I deliberately write the system, is easy to understand, since this system refers to the shell, then a script using/bin/sh as an interpreter can save the first line? Yes.

Three: Experience

(1) Simply say the shell is a file containing several lines of shell or Linux commands. For a large number of commands that are written and used more than once, you can use a separate file to save it for later use.
For example: You write a project in C, there are many. h files,. c files and so on, each change you need to re-g++ filenames.c filenames.h-o filenames, too troublesome, then you need to write a small shell file, can solve the problem.

(2) Remember that the last time I wrote the basic Python learning, it should be one months ago, this time to re-learn a new language (scripting language), the interval is very short, more and more feel, must master a language, then learn other languages very easy to get started-just a primer, If you want to advance in a certain language or in-depth, can only say "long way to repair the far-away"!

(3) I am not fraught here, detailed shell introduction See Bird's home cuisine or shell script tutorial

0 Basic Learning 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.