Shell Programming Basics

Source: Internet
Author: User
Tags arithmetic operators shebang

When it comes to programming, we are all not unfamiliar, but in Linux, we mainly do script writing. Of course, in order to understand the scripting of Linux, we have to first say the logical relationship of multi-command execution.

1. Command replacement

COMMAND1 $ (COMMAND2)

2. Piping

COMMAND1 | COMMAND2 |

3. Sequential execution structure

COMMAND1; COMMAND2; COMMAND3;

4. Select the execution structure:

If... So...

Either... Either...

The main thing is the logical operation structure, we all know the logical operation is with or not, so from these three points.

1) with: logical multiplication, true, 0--false, Bash, &&, binocular operator

1 && 1=1

1 && 0=0

0 && 1=0

0 && 0=0

Short-circuit algorithms for "and" operations: as long as the first operand is flase, the result of its logical operation must be false;


2) OR: logical addition, 0--, fake, bash, | |, binocular operator

1 | | 1=1

1 | | 0=1

0 | | 1=1

0 | | 0=0

"or" Operation Short-circuit law: As long as the first operand is ture, then its logical operation result must be ture;


3) Non: Logical inversion, True, 0--false,! , single-mesh operator;

!0=1

!1=0

The execution status return value of the command:

Success:0--ture

Failure:1-255--false


Of course, in Linux we mainly use command Line Input command to operate the Linux system, so we are mainly for the command to implement and or non-logical operation.


With: COMMAND1 && COMMAND2

Said:

1. If COMMADN1 can execute successfully, COMMAND2 will be executed;

2. If COMMADN1 execution fails, then COMMAND2 will not be executed;


Or: COMMAND1 | | COMMAND2

Said:

1. Only COMMAND1 execution fails, COMMAND2 will be executed;

2. If the COMMADN1 is executed successfully, then COMMAND2 will not be executed;

Non: (General and mixed use)

! COMMAND1 && COMMAND2 equivalent to COMMAND1 | | COMMAND2

! COMMAND1 | | COMMAND2 equivalent to COMMAND1 && COMMAND2


Priority of three logical operations:

! > && > | |


Example:

If the user user4 exists and the home directory also exists, then the Userdel-r USer4 command is executed;

ID user4 && ls-d/home/user4 && userdel-r USer4



A brief introduction to the logical relationship of multi-command execution, let's say bash script programming.

What do you mean by programming?

The process of writing program source code using human natural language or machine language.


Why do you want to program?

In order to enable users to use the computer, you can let the computer do some tasks in a non-interactive way, the user needs to edit such tasks into a file, and let the computer in a specific order to read the task, so as to achieve the expected function;


In order for the computer to interpret the contents of such a file and execute it correctly, the program source code file must be converted to a binary format that the computer can directly recognize and use, which is called compiling, and you must use a specific compiler tool to complete the compilation process, so no matter what programming language you use to write the program, Must be programmed according to the specific format and grammatical structure that the compiler can recognize;


The programming languages we have learned so far are: high-level languages, low-level languages, and machine languages. There are different categories of high-level language separations in different ways:

1, according to the source code processing method Classification:

1) compiler language, main process:

Source code---Compiler processing (compilation)----[Linker (link)]----Assembler (assembler)---Executable binary code file;

2) Explanatory language

The source code---Interpreter (line-by-row interpretation)--side interpretation edge execution.

2, according to the functional implementation in the programming process is called the library or external program files to classify:

Complete programming Language:

Programming using a library or programming component;

Script programming Language:

Use the interpreter to invoke the selected external application;

3, according to the Code classification of the program:

Programming Language:

program = instruction + data

Command-centric, around the function of the instruction to achieve the design data and data structure, information for the command service;

Algorithm and instruction implementation form:

Sequential execution

Select Execute

Loop execution

Object-Oriented languages:

program = algorithm + data structure

The data and structure are the center, the data is instantiated, and the algorithm is deployed around the requirement of data;

Class: the data being instantiated;

Attribute (Atribution): The basis of distinguishing different objects in the same class;

Method (Mathod): The correct operation method of the class;

Low-level language is mainly assembly language, machine language is mainly binary language. While the Bash scripting language is different from these programming languages, it is a procedural programming language that interprets the running programming language, the scripting language (which relies on external application files to run). With all that said, what exactly is the bash script? How exactly did he write it? What is the difference between its code writing format and the programming language we normally use? Let's talk about it next.


What exactly is a bash script?

1. Plain text Document--all the stored or contained data instruction + data in a file is stored in characters;

2. Simple or complex command combination to solve user's problem according to user's requirement;

3. is a procedural entity with the "power of Execution";

Execute idempotent: The result of one execution of any command is consistent with the result of multiple execution;

Note: Many commands do not have "idempotent", so there is a need to use a lot of program logic in the shell script to determine whether a command conforms to its operating conditions, thus avoiding the critical errors that occur during the run.


Second, how to write the contents of the shell script?

1. The first line must be shebang, that is: the absolute path of the interpreter program, must occupy the absolute beginning of the line and must occupy the first row, in the execution of the script, according to the instructions of shebang, the corresponding interpreter is started to explain the script is a lot of commands;

#!/bin/bash

2. In the shell script, all lines that start with the # character, except Shebang, are interpreted as comment lines, that is, the interpreter interprets its contents but does not execute;

3. The interpreter ignores all blank lines in the script file; a blank line refers to a line in a line of text, except for whitespace characters, space characters, and tab characters that do not have any other type of character;

4. Lots of commands and keywords

Command: internal or external applications;

Keywords: commands built into the shell that can only be executed in a particular structure; keyword;

such as: If,else,then,do,while,for,select,until,fi,esac, ...

5. Contains all the special function characters in the shell;


Note: All commands, keywords, and symbols written into the shell script document must be in ASCII-encoded format, and other encoded characters may appear in the shell script file without any special meaning;


Third, how to write shell script?

You can use all the text document editing tools for Shell scripting, such as: Nano,vi,vim,pico,emacs, ...


Vim is typically recommended for each release of Linux;


Command mode for the script file:

In general, the name suffix of ". Sh" will be set for the script, and the lower version of the editing tool will identify whether it is a shell script file based on the suffix name of the file, and the higher version of the text editing tools, such as VIM7, can ignore such a name difference; there is no need to worry too much about file suffix names 。

We know how to write, and its format requirements, and so on a series of questions, so how should we let it run up?

How the script runs:

1. Give execute permission to the script file, which can be run directly in absolute path or relative path;

# chmod +x/path/to/some_script_file

#/path/to/some_script_file

Note: If the directory path where the script file resides is stored in the path variable, it is executed directly with the script file name;


2. Run the script directly using the interpreter and use the script file as the parameter of the interpreter program;

# Bash/path/to/some_script_file

Common options for Bash commands;

-X: Enables bash to interpret the script in the standard output, and is generally used to debug the shell script;

-N: The script file is pre-executed to parse the script for syntax-class errors, and if there is no error, no information is output;


Note: In this way, whether the script file has execute permissions is not a very important property;


Note: In both of these ways, when the script is executed, a new child shell is opened in the current shell to run the script, and in general, the child shell is destroyed as soon as the script is run, so all variables defined in the script, at the end of the script, should be explicitly revoked; uns ET undo variable. GC garbage collection.



3. Use the source command to run the script:

# Source/path/to/some_script_file

#  . /path/to/ome_script_file


Attention:

The 1.source command no longer runs the script when the child shell is opened, but runs in the current shell;

2. Do not include commands such as the exit class in scripts executed with the source command, (most likely the current shell is logged off, the properties you set are reset, etc.)


Write a script:

Created when the Alex user does not exist, or if it is successfully created, displays the prompt message that was created successfully, or the user already exists.

[Email protected] ~]# vim a.sh#!/bin/bash#! ID Alex && useradd Alex && echo "User Alex is here" | | echo "Alex is already." [Email protected] ~]# bash a.sh id:alex:no such useruser Alex are here


We can use the Bash script to implement arithmetic operations:

Arithmetic operator:

Commonly used basic arithmetic operators:

+,-,*,/,%,**


Enhanced arithmetic operators:

+=,-=,*=,/=,%=


Special Enhanced Arithmetic operators:

++,--


Arithmetic Operation Method:

1.$[exipression]

The expression can be made up of pure numbers, or you can use variables to reference variable values, and you can omit the ' $ ' symbol when using a variable;


Example:

# echo $[3+4]

# Num1=5;num2=4;echo $[num1+num2]


2.let var=expression

The arithmetic operation is completed according to the arithmetic expression and assigned to the specified variable;


3.$ ((EXPRESSION))

The expression can be made up of pure numbers, or you can use variables to reference variable values, and you can omit the ' $ ' symbol when using a variable;


4.expr ARGUMENT1 ARGUMENT2 ARGUMENT3

where ARGU1 and ARGU3 must be integer values; ARGU2 is the arithmetic operator;



5.echo "EXPRESSION" | BC

[Email protected] ~]# echo "SCALE=3;35/7" | bc5.000



6.bc <<< "EXPRESSION"

[email protected] ~]# BC <<< "SCALE=5;40/7" |bc5.71428


For example:

[Email protected] ~]# vim a.sh#!/bin/bash#num1= "' ls/etc | Wc-l ' "num2=" ' Ls/var | Wc-l ' "num3=" ' ls/usr | Wc-l ' let sum= $num 1+ $num $num 3echo "$sum" [[email protected] ~]# bash a.sh310


Shell Programming Basics

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.