Getting Started with Linux-basic shell

Source: Internet
Author: User
Tags aliases arithmetic exit in

Shell scripting language is an important tool to implement LINUX/UNIX system management and automation operations, and the core of the Linux/unix system is mostly concerned with the contents of shell scripts. Every qualified Linux system administrator or OPS engineer needs to be able to skillfully write the Shell scripting language and be able to read the shell script content that comes with the system and various types of software. Only in this way can we improve the efficiency of operation and maintenance personnel, adapt to the complex work environment, reduce unnecessary duplication of work, so as to lay a better foundation for personal career development

1 Types of scripting languages 1.1 compiled languages

Refers to the use of a dedicated compiler for a specific operating platform (operating system) to translate a high-level language source code into a hardware platform directly run by the binary machine code (with operands, instructions, and the corresponding format), this process is called compilation (./configure Make Makeinstall ); A compiled executable file (. exe) that can run on a relative platform (poor portability, but high efficiency).

Typical compiled languages are, C language, C + +, and so on.

In addition, the Java language is a very special language, the Java program needs to compile steps, but does not generate a platform-specific binary machine code, it compiles a platform-independent bytecode file (*.class) (The reason for good portability), such bytecode can not be directly executed by the platform, The runtime needs to be interpreted by the interpreter as a binary machine code file of the corresponding platform; most people think Java is a compiled language, but we say that Java is a compiled language, and it is also an interpreted language.

1.2 Explanatory language

A language in which the source program is interpreted on a line-by-row basis and executed immediately by a specialized interpreter, which is equivalent to mixing the compiled-link process of a compiled language together.

Interpreted language execution is inefficient and cannot be run out of the interpreter, but its cross-platform type is relatively easy and requires only a specific interpreter.

Common explanatory languages include Python (also scripting language) and Ruby.

2 Script Writing Specifications

1) put in a unified directory

2) script with. sh extension

3) Specify the script interpreter at the beginning.

4) Information such as the beginning and version copyright.

5) The script should not be commented in Chinese, try to comment in English. (may be garbled due to compatibility issues)

6) Code writing good Habits

A, the content of the paired to write at once, to prevent omission, such as [], "," "and so on

b, [] at both ends to have a space, first enter [], backspace, enter 2 spaces, and then backspace write.

D. Make the code easy to read by indenting.

F, the quotation marks in the script are the quotation marks in the English state, the other characters are also the English state

Execution of 3Shell scripts

1 Adding Execute permissions to scripts chmod +x XXX

2 Execute script./xxx. XXX source xxx (current directory)

4 variables

Variable: named memory space

How data is stored:

Role:

1. Data storage format

2, the operation of the participation

3, the data range indicated

Type:

Strongly typed: The variable is not cast, it is always the data type, and the implicit type conversion is not allowed. You must specify a type when defining a variable, the join operation must conform to the type requirement; Calling an undeclared variable produces an error

such as java,c#

Weak type: The runtime of the language implicitly does the data type conversion. You do not need to specify a type, the default is character type, the participating operation will automatically do the implicit type conversion, the variable can be called directly without prior definition

such as: Bash does not support floating-point numbers, PHP

Variable naming laws:

1. Cannot make reserved words in the program: for example if, for

2, only use numbers, letters and underscores, and cannot start with a number

3. See the meaning of the name

4, the Uniform naming rule: Hump name method (first letter lowercase, the rest of the first letter of the word capital)

4.1 Common variables

Local variables are used in scripts for the user's current shell lifetime. For example, the local variable Oldboy value is Bingbing, which is meaningful in the user's current shell lifetime. If you start another process or exit in the shell, the local variable value will not be valid

Variable definition

(1) can be a direct string; Name= "Root"

(2) Variable reference: name= "$USER"

(3) Order reference: Name= ' command ' name=$ (command)

Variable references:

${name} $name

Show all variables that have been defined: set

Delete variable: unset name

4.2 Environment variables

Variable reference: $name, ${name}

Show all environment variables:

Env

Printenv

Export

Declare-x

To delete a variable:

unset name

Bash built-in environment variables:

–path–shell–user–uid–home

–pwd–shlvl–lang–mail–hostname

–histsize

Calling parameters passed to the script from the command line in script code

$, $, ... : corresponding to 1th, 2nd and other parameters

4.3 Special variables

Special variables:

Positional variables:

$ $ Gets the file name of the currently executing shell script, including the script path if the script is executed with a path.

$n gets the nth parameter value of the currently executing shell script, n=1..9, which represents the file name of the script when n is 0, and if n is greater than 9 enclosed in curly braces {10}, the parameters are separated by a space.

$* gets all parameters of the current shell's arguments, without quotation marks with [email protected]; If you add double quotes to $*, for example: "$*", all arguments are treated as a single string, equivalent to "112$3"

[Email protected] Gets the parameters of all arguments for the current shell, without quotation marks and $*, and if [email protected] is given a double quotation mark, for example: "[email protected]", it means that all parameters are treated as distinct separate strings. The equivalent of "$" "$" "$" "...", which is the best way to pass parameters to other programs because he retains any whitespace embedded in each parameter.

$# gets the total number of parameters that are followed by the currently executing shell script

When both "$*" and "[email protected]" are double-quoted, there is no difference between the two, without double quotes.

Process state variables

$? Gets the execution state return value that executes the last instruction (0 for success, nonzero for failure), which is most commonly used

$$ Gets the process number (PID) of the currently executing shell script, this variable is not used

4.4 Methods for defining variables

1, directly assigned value

A=lisi

Export a= Lisi (global variable)

2. Parameter transfer (transfer parameters)

A = "$UASE"

3. Interactively set variables, using the Read command

Use read to assign input values to one or more shell variables

-p Specifies the prompt to display

-s silent input, commonly used for passwords

n n Specifies the character length of the input

-d ' character ' input terminator

-T n timeout is n seconds

Read reads values from standard input, assigns a variable to each word all remaining words are assigned to the last variable

Read-p "Enter a filename:" FILE

Exercise : Write a script with the name/root/bin/createsh.sh, and when executing it, execute a method such as/root/bin/createsh.sh backup.sh, after execution, in/root/ A file named backup.sh is generated under the bin with the following line,

#!/bin/bash

# ------------------------------------------

# Filename:xx.sh

# revision:1.0

# date:2017/06/01

# author:xxx

# email: [Email protected]

# Website:www.XXXXX.com

# Description:

# ------------------------------------------

The file is then automatically opened with Vim, and the cursor is located directly under the non-comment section of the new line Vim + open vim to the last line

5 Arithmetic 5.1 arithmetic operation

Arithmetic operations in bash:

+,-, *,/,% remainder, * * (exponentiation)

Operations that support integers only

echo $ ((mathematical expression))

Let command

$[] Operator

Commands that can perform decimal operations

BC Command

awk command

Self-increment, self-reduction:

Let a+=1 = Let b++

Let b-=1 = Let B

Practice

5.2 Logical Operations

True, False

1, 0

And:

1 and 1 = 1 1 with 0 = 0

0 and 1 = 0 0 with 0 = 0

Or:

1 or 1 = 1 1 or 0 = 1

0 or 1 = 1 0 or 0 = 0

Non -:!

! 1 = 0! 0 = 1

Short circuit operation

Short Circuit and

The first one is 0, and the result must be 0.

The first one is 1, the second must be involved in the operation

Short Circuit or

The first one is 1, and the result must be 1.

The first one is 0, the second must be involved in the operation

XOR: ^

XOR two values, same as false, different for true

5.3-Piece operation

Depending on the exit status, the command can be run conditionally

&& represents conditional and then

|| Represents a conditional or ELSE

For example:

grep-qno_such_user/etc/passwd\| | Echo ' Nosuchuser '

Nosuchuser

Ping-c1-w2station1&>/dev/null\>&&echo "Station1isup" \>| | (Echo ' station1isunreachable '; exit1)

Station1isup

5.4 Numerical Tests

Numerical test:

-GT is greater than

-ge is greater than or equal to

-eq is equal to

-ne is not equal to

-lt is less than

-le is less than or equal to

5.5 String test

String test:

= = is equal to

> ASCII code is greater than ASCII code

< is less than

! = is not equal to

=~ whether the left string can be matched by the pattern on the right

Note: This expression is typically used in [[]]; extended regular expressions

-Z "string" string is empty, empty is true, not empty is false

-N "string" string is not empty, not empty is true, empty is false

Note: The operands used for string comparisons should all use quotation marks

5.6 File Test

Presence Testing

-a FILE: Same-E

-e File: Test for existence of files, existence is true, otherwise false

Presence and category Testing

-B File: Exists and is a block device file

-C file: exists and is a character device file

-D file: Exists and is a catalog file

-F file: exists and is a normal file

-H file or-L file: Existing and Symbolic link files

-P file: exists and is a named pipe file

-S file: exists and is a socket file

File permission test:

-R FILE: exists and is readable

-W FILE: exists and is writable

-X FILE: exists and is executable

File Special Permissions Test:

-U FILE: Exists and has suid permissions

-G FILE: Exists and has Sgid permissions

-K FILE: Exists and has sticky permissions

File size test:

-S FILE: exists and is not empty

Whether the file is open:

-T FD:FD file descriptor is already open on a terminal

-N File: Whether the file has been modified since the last time it was read

-O File: Whether the current active user is a file owner

-G file: whether the current active user is a group of files

Binocular test:

Whether File1-effile2:file1 is a hard link to FILE2

Whether File1-ntfile2:file1 is new to FILE2 (Mtime)

File1-otfile2:file1 is older than FILE2

Practice

1 Write script/root/bin/excute.sh, determine whether the parameter file is the sh suffix of the ordinary file, if yes, add everyone can execute permissions, otherwise prompt the user non-script file

2 Scripting/root/bin/nologin.sh and login.sh, implement prohibit and allow ordinary user login system

Login is similar to this one, so I don't write it.

6 preventing extended 6.1Bash How to expand the command line

Split the command line into a single command word--expand aliases--expand curly Braces declaration ({})--Expand Tilde Declaration (~)--and command to replace $ () and ")--then divide the command line into command words--expand File Wildcard (* 、?、 [ABC ]--Ready to i/0 redirect (<, >)--Run command

6.2 Preventing expansion

A backslash (\) causes subsequent characters to be interpreted as intended

$echoYourcost: \$5.00

yourcost:$5.00

Quotation marks to prevent extension

Single quotation mark (') prevents all extensions

Double quotation marks (") also prevent all extensions, but the following exceptions apply:

$ (dollar sign)-variable extension

' (anti-quote)-command substitution

\ (backslash)-suppresses single character expansion

! (exclamation mark)-Historical command replacement

Configuration file for 7Bash

In terms of effective scope, there are two categories:

Global configuration:

/etc/profile

/etc/profile.d/*.sh

/etc/bashrc

Personal configuration:

~/.bash_profile

8Shell method of Landing

Interactive login:

(1) Enter the account password directly through the terminal login

(2) Users who switch with "Su-username"

Order of execution:/etc/profile-/etc/profile.d/*.sh-~/.bash_profile--> ~/.bashrc-->/ETC/BASHRC

Non-interactive logon:

(1) Su UserName

(2) The terminal opened under the graphical interface

(3) Execute script

(4) Any other bash instance

Execution Order:~/.bashrc-->/etc/bashrc-->/etc/profile.d/*.sh

9 Configuration Files

Profile class

Global:/etc/profile,/etc/profile.d/*.sh

Personal: ~/.bash_profile

Function:

(1) for defining environment variables

(2) run a command or script

BASHRC class

BASHRC class: Provides configuration for non-interactive and interactive logon shells

Global:/ETC/BASHRC

Personal: ~/.BASHRC

Function:

(1) Defining command aliases and functions

(2) Defining local variables

How the configuration file takes effect

After you modify the profile and BASHRC file, it takes effect

Two methods:

1 restarting the shell process

2. or source

Cases:

. ~/.bashrc

Attached:. Differences from source to./

./script runs the script as an executable file, launches a child shell to run it, and then returns to the parent shell after executing the script, so all operations performed in the child shell do not affect the parent shell;

. script and source script read and execute commands from the file name in the current shell environment.

When using./Run scripts, system variables are not affected, while using source and. Will affect the current environment variables of the system.

Practice

1 scripting/root/bin/systeminfo.sh, displaying current host system information, including hostname, IPV4 address, operating system version, kernel version, CPU model, memory size, hard disk size

2 Scripting/root/bin/backup.sh for daily/etc/directory backup to/root/etcyyyy-mm-dd

3 Writing the user's environment initialization script reset.sh, including aliases, login prompt, vim settings, environment variables, etc.

Getting Started with Linux-basic shell

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.