Bash Shell and bashshell

Source: Internet
Author: User

Bash Shell and bashshell
I,Terminal Printing

[Root @ cai ~] # Echo welcome to bash!

Welcome to bash!

 

[Cairui @ cai ~] $ Echo 'Welcome to bash! '

Welcome to bash!

 

[Cairui @ cai ~] $ Echo "welcome to bash \! "

Welcome to bash \!

(Note: special characters cannot be directly used in double quotes. escape characters must be used \)

 

[Cairui @ cai ~] $ Printf "hello world"

Hello world

 

#! /Bin/bash

# Filename: printf. sh

 

Printf "%-5 s %-10 s %-4s \ n" no name mark

Printf "%-5 s %-10 s %-4.2f \ n" 1 sarath 80.3456

Printf "%-5 s %-10 s %-4.2f \ n" 2 james 90.9989

Printf "%-5 s %-10 s %-4.2f \ n" 3 jeff 77.564

The following result is displayed.

[Cairui @ cai shell] $ sh printf. sh

No name mark

1 sarath 80.35

2 james 91.00

3 jeff 77.56

 

1. Working Principle

% S, % c, % d, and % f are both format replacements. The parameters corresponding to them can be placed after the format string with quotation marks.

%-5s indicates that the string in the left-aligned format and with a width of 5 is replaced. If not, use a space.

For %-4.2f,. 2 indicates that 2 decimal places are reserved.

2. Additional content

(1) escape line breaks in echo

[Cairui @ cai shell] $ echo-e "1 \ t2 \ t3"

1 2 3

(2) print the color output

Reset = 0, black = 30, Red = 31, Green = 32, yellow = 33, Blue = 34, Magenta = 35, cyan = 36, white = 37

Print color text

 

[Cairui @ cai shell] $ echo-e "\ e [1; 31 m this is red text \ e [0 m"

This is red text

 

Set color background, reset = 0, black = 40, Red = 41, Green = 42, yellow = 43, Blue = 44, Magenta = 45, cyan = 46, white = 47

 

 

II, Fun variables and Environment Variables

In bash, the value of each variable is a string. No matter whether you assign a value to a variable without quotation marks, the value is in the form of a string. Some special variables are used by shell and operating system environments to store some special values. These variables are called environment variables.

Cat/proc/$ PID/environ (view runtime environment variables)

Example:

[Cairui @ cai shell] $ pgrep mysql

11029

11313

[Cairui @ cai shell] $ sudo cat/proc/11313/environ

TERM = xtermOLDPWD =/application/mysqlPATH =/sbin:/usr/sbin:/bin:/usr/bin: /application/mysql/binPWD =/application/mysqlSHLVL = 3MYSQL_HOME =/application/mysql _ =/usr/bin/nohup

[Cairui @ cai shell] $ sudo cat/proc/11313/environ | tr '\ 0'' \ N'

TERM = xterm

OLDPWD =/application/mysql

PATH =/sbin:/usr/sbin:/bin:/usr/bin:/application/mysql/bin

PWD =/application/mysql

SHLVL = 3

MYSQL_HOME =/application/mysql

_ =/Usr/bin/nohup

 

1. Practical drills

 

[Cairui @ cai shell] $ var = value

[Cairui @ cai shell] $ echo $ var

Value

 

The Variable. sh code is as follows:

#! /Bin/bash

Fruit = apple

Count = 5

Echo "we have $ count $ fruit (s )"

[Cairui @ cai shell] $ sh variable. sh

We have 5 apple (s)

 

The Export command is used to set environment variables:

[Cairui @ cai shell] $ echo $ PATH

/Application/mysql/bin:/usr/local/sbin:/usr/sbin: /application/xtrabackup/bin:/home/cairui/bin

[Cairui @ cai shell] $ export PATH = "$ PATH:/home/cairui"

[Cairui @ cai shell] $ echo $ PATH

/Application/mysql/bin:/usr/local/sbin:/usr/sbin: /application/xtrabackup/bin:/home/cairui

 

2. Additional content

Length =$ {# var}

For example:

[Cairui @ cai shell] $ vai = 1234567890

[Cairui @ cai shell] $ echo $ {# vai}

10

 

III, Add environment variables using functions

PATH =/usr/bin;/bin

This means that when the shell needs to execute a binary executable file, it will first find/usr/bin, then/bin

 

IV, Use shell for mathematical operations

In the bash shell environment, you can use let, [], () to perform basic arithmetic operations. The expr and bc tools are also useful for advanced operations.

1. Instance

#! /Bin/bash

# Filename: jia. sh

No1 = 4;

No2 = 5;

Let result = no1 + no2

Echo $ result

[Cairui @ cai shell] $ sh jia. sh

9

Auto-add operation

Let no1 ++

Auto-Subtraction

Let no1 --

Abbreviated form

Let no + = 6

Let no-= 6

They are equal to let no = no + 6 and let no = no-6, respectively.

(2) bc is an advanced mathematical tool. This precision calculator contains many options.

 

[Root @ cai ~] # Echo "4*8" | bc

32

 

No = 54

Result = 'echo "$ no * 1.5" | bc'

Echo $ result

81.0

L sets the decimal precision. In the following example, scale = 2 sets the number of decimal places to 2.

[Cairui @ cai shell] $ echo "scale = 2; 3/8" | bc

. 37

Hexadecimal conversion. Bc can be used to convert one hexadecimal system to another. (Decimal to decimal)

#! /Bin/bash

# Purpose: Digital Conversion

 

No = 100

Echo "obase = 2; $ no" | bc

 

No = 1100100

Echo "obase = 10; ibase = 2; $ no" | bc

[Cairui @ cai shell] $ sh shuzizhuanhuan. sh

1100100

100

L calculate square and square root

[Cairui @ cai shell] $ echo "sqrt (100)" | bc

10

 

[Cairui @ cai shell] $ echo "10 ^ 10" | bc

10000000000

 

V, Game file descriptor and redirection

A file descriptor is an integer associated with the input and output of a file. They are used to track opened files. The most common file descriptors are stdin (standard input), stdout (standard output), and stderr (standard error ).

0 ----- stdin

1 ----- stdout

2 ----- stderr

1. Instance

[Cairui @ cai shell] $ echo "this is a sample text"> temp.txt

[Cairui @ cai shell] $ cat temp.txt

This is a sample text

[Cairui @ cai shell] $ echo "this is a sample text"> temp.txt

[Cairui @ cai shell] $ cat temp.txt

This is a sample text

This is a sample text

When an error occurs in the command, the error message is printed.

 

[Cairui @ cai shell] $ ls +

Ls: cannot access +: No such file or directory (error message)

 

2. Working Principle

> Equivalent to 1>; For> is also equivalent to 1>

(1) redirect the file to the command

Cmd <file

(2) Redirect text blocks inside the script

#! /Bin/bash

Cat <EOF> log.txt

LOG FILE HEADER

This is a test log

Function: system statistics

EOF

 

[Cairui @ cai shell] $ sh log-txt.sh

[Cairui @ cai shell] $ cat log.txt

LOG FILE HEADER

This is a test log

Function: system statistics

 

VI, Arrays and associated Arrays

Array_var = (1 2 3 4 5 6) # these values are stored in the continuous position where the index starts with 0.

You can also define an array as a set of "index-value"

Array_var [0] = "test1"

Array_var [1] = "test2"

......

......

......

......

Array_var [5] = "test6"

 

Echo $ array_var [0]

Test1

 

Echo $ array_var [*]

Test1 test2 test3 test4 test5 test6

 

Print array Length

Echo $ {# array_var [*]}

6

 

VII, Use alias

(1) You can create an alias using the following methods:

Alias new_command = 'COMMAND sequence'

(2) The alias is temporary. To make the alias take effect permanently, you can place it in ~ /. Bashrc File

Echo 'Alias cmd = "commadn seq" '> ~ /. Bashrc

(3) to delete an alias, you only need ~ /. Delete the file in bashrc.

 

8, Obtain terminal information

Tput and stty are two terminal processing tools.

1. Instance

L obtain the number of rows and columns of the terminal:

Tput cols

Tput lines

L print the current terminal Name:

Tput longname

L move the cursor to the coordinate (100,100:

Tput cup 100 100

L set the terminal background color:

Tputsetb n

Where, n can be between 0 and 7.

L set the text style to bold

Tput bold

L set the start and end of the underline:

Tput smu1

Tput rmu1

L delete all content from the current cursor position to the end of the row:

Tputed

L when entering the password, the entered content should not be displayed:

#! /Bin/bash

# Filename: password. sh

Echo-e "enter password :"

Stty-echo

Read password

Stty echo

Echo

Echo password read

 

9. Get and set the date and delay

Many programs need to print the date in different formats, set the date and time, and perform operations based on the date and time. Latency is usually used to provide a wait time (for example, 1 second) during program execution ). For example, to monitor a task every five seconds in the script, you need to know how to add latency to the program.

1. Instance

(1) [cairui @ cai support-files] $ date

Tue Jun 6 15:27:22 CST 2017

(2) print the epoch:

[Cairui @ cai support-files] $ date + % s

1496734094

 

[Cairui @ cai support-files] $ date -- date "jan 20 2011" + %

Thursday

(3) format string combination + as the parameter of the date command:

[Cairui @ cai support-files] $ date "+ % d % B % y"

06 Jun 17

(4) set the time and date:

Date-s "formatted date string"

Example:

Date-s "21 June 2009 11:01:22"

(5) sometimes we need to check the time spent by a group of commands. The following code:

#! /Bin/bash

# Filename: time_take.sh

Start = $ (date + % s)

Commands;

Statements;

 

End = $ (date + % s)

Difference = $ (end-start ))

Echo time taken to execute commands is $ difference seconds

2. Working Principle

Date content

Format

Week

% A ()

Month

% B (B)

Day

% D

Fixed format date (mm, dd, yy)

% D

Year

% Y (Y)

Hours

% I or % H

Minutes

% M

Seconds

% S

Nanoseconds

% N

Unix epochs (in seconds)

% S

 

 

3. Additional content

In the script, you can use sleep; $ sleep no_of_seconds. For example, the following script uses tput and sleep to count from 0 to 40:

#! /Bin/bash

# Filename: sleep. sh

Echo-n Count: (echo-n outputs without line breaks)

Tput SC

 

Count = 0;

While true;

Do

If [$ count-lt 40];

Then

Let count ++;

Sleep 1;

Tput rc

Tput ed

Echo-n $ count;

Else exit 0;

Fi

Done

In the preceding example, the variable count is initialized to 0, and then the 1. echo statement is added once every cycle to print the value of count. Use tput SC to store the cursor position. In each loop, print the new count value in the terminal by restoring the previously stored cursor position. The command to restore the cursor is tput rc. Tput ed clears all content from the current cursor position to the end of the row, so that the old count value can be cleared and new values can be written. The 1-second delay in a loop is achieved through the sleep command.

 

10, Debug scripts

(1) bash-x script. sh or sh-x script. sh

(2) Use set-x and set + x to partially debug the script. For example:

#! /Bin/bash

# Filename: debug. sh

For I in {1 .. 6 };

Do

Set-x

Echo $ I

Set + x

Done

Echo "script executed"

[Cairui @ cai shell] $ sh debug. sh

+ Echo 1

1

+ Set + x

+ Echo 2

2

+ Set + x

+ Echo 3

3

+ Set + x

+ Echo 4

4

+ Set + x

+ Echo 5

5

+ Set + x

+ Echo 6

6

+ Set + x

Script executed

In the above script, only the debugging information of echo $ I is printed. -X and + x are used to limit the debugging area.

(3) Both of the preceding debugging methods are built-in. They usually generate debugging information in a fixed format. However, in many cases, we need to display debugging information in a custom format. This type of debugging style can be created by passing the _ DEBUG environment variable.

#! /Bin/bash

Function DEBUG ()

{

["$ _ DEBUG" = "on"] & &$ @ |:

 

}

For I in {1 .. 10}

Do

DEBUG echo $ I

Done

~

[Root @ cai shell] # _ DEBUG = on./DEBUG. sh

1

2

3

4

5

6

7

8

9

10

We add DEBUG before every statement that needs to print debugging information. If _ DEBUG = on is not passed to the script, the debugging information will not be printed. In bash, the command ":" tells shell not to perform any operation.

 

XI, Functions and Parameters

1. Instance

You can create a function to execute a specific task or a function that accepts parameters.

(1) define functions:

Function fname ()

{

Statements;

}

Or

Fname ()

{

Statements;

}

(2) You only need to use the function name to call a function:

$ Fname # execution function

(3) parameters can be passed to functions and accessed by scripts:

Fname arg1 arg2; # Transfer Function

The following is the definition of the function fname. The function fname contains methods for accessing function parameters.

Fname ()

{

Echo $1, $2; Access parameter 1 and parameter 2

Echo "$ @"; print all parameters in a list at a time

Echo "$ *"; similar to ¥ @, but the parameter is used as a single entity

Return 0; return Value

}

L $1 is the first parameter

L $2 is the second parameter

L $ n is the nth Parameter

L "$ @" is extended to "$1" "$2" "$3" and so on.

L "$ *" is extended to "$ 1c $ 2c $3", where c is the first character of IFS

L "$ @" is more than $.

2. Additional content

(1) recursive functions

F () {echo $1; f hello; sleep 1 ;}

(2) Export Functions

Export-f fname

 

12, It is not applicable to the carriage return key to read n characters.

Read is an important bash command used to read text from a keyboard or standard input. We can use read to read user input in interactive form, but read can do more than that. Most input libraries in any programming language read input from the keyboard. However, the input is completed only when the Enter key is pressed. In some games, you only need to press q to release the skills.

(1) The following statement reads n characters from the input and stores the variable variable_name;

Read-n number_of_chars variable_name

For example:

Read-n 2 var

Echo $ var

(2) read the password without ECHO:

Read-s var

(3) display prompt information:

Read-p "enter input:" var

(4) read input within a specific time range:

Read-t timeout var

 

Read-t 2 var # read the entered string into the variable var within 2 seconds

(5) Use a specific delimiter as the end of the input line:

Read-d delim_char var

 

Read-d ":" var

Hello: # var is set to hello

 

XIII, Run the command until the execution is successful.

When shell is used in daily work, sometimes commands can be successfully executed only when certain conditions or an external event (for example, an object can be downloaded) are met. In this case, you may want to execute the command again until it is successful.

1. instance:

Define a function as follows:

Repeat ()

{

While true

Do

$ @ & Return

Done

}

Or put it into the shell rc file for better use:

Repeat () {while true; do $ @ & return; done}

2. Working Principle

We have created a function repeat, which contains an infinite while loop. This loop executes the command to pass in the function in the form of parameters (accessed through $. If the command is successfully executed, return, and then an infinite loop.

3. Additional content

(1) A faster approach

Repeat () {while:; do $ @ & return; done} faster than the first method

(2) increase latency

Repeat wget-c ........

Repeat () {while:; do $ @ & return; sleep 30; done} This allows the command to run every 30 seconds.

14th, Loop

(1) for Loop

For var in list;

Do

Commands;

Done

(2) while Loop

While condition

Do

Commands;

Done

(3) until Loop

It loops until the given condition is true.

X = 0;

Until [$ x-eq 9];

Do

Let x ++; echo $ x;

Done

 

15th, Comparison and Testing

1. Practice

(1) if condition

If condition;

Then

Commands;

Fi

(2) else if and else

If condition;

Then

Commands;

Else if condition; then

Commands;

Else

Commands;

Fi

(3) arithmetic comparison

L perform arithmetic condition judgment on variables or values:

[$ Var-eq 0] # returns true if $ var is equal to 0.

[$ Var-ne 0] # When... Returns true if the value is not 0.

L-gt: greater

L-lt: less

L-ge: greater than or equal

L-le: less than or equal

(4) string comparison

When comparing strings, we recommend that you use double brackets, because sometimes errors may occur when using single brackets, so it is best to avoid them.

L [[$ str1 = $ str2], returns true

L [[$ str1 = $ str2] Another way to check whether the string is equal

L [[$ str1! = $ Str2] returns true if str1 and str2 are different

L [[$ str1> $ str2]

L [[$ str1 <$ str2]

L [[-z $ str1]. If it contains an empty string, the return value is true.

L [[-n $ str]. If the string contains a non-null string, true is returned.

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.