Shell Scripting Tips

Source: Internet
Author: User
Tags case statement echo command

What is a shell script, first of all it is a script, and not as a formal programming language, so to speak is that the shell script is a collection of commands.

All custom scripting recommendations are placed in the/usr/local/sbin/directory, and the benefits are easy to manage and maintain, and facilitate later handover to your replacement administrator.

The structure of the shell script

#cat first.sh

#! /bin/bash

# # This is my first shell script.

Date

echo "Hello world!"

The script should be #! The/bin/bash begins with the meaning that the file is using bash syntax, which is OK if you do not use the line, but if you put the script in a system where the default shell is not bash, the script will probably not execute successfully.

You can also use # in scripts to write some script-related comment content, such as author, creation date, or version. These are not the shell scripts must be, just for unified management, normalization.


Several ways to execute shell scripts

    1. Fork: Executes the script directly using an absolute path, which starts a child shell to execute the script.

    2. SOURCE filename: Reads and executes the commands in the filename in the current shell environment. Note: This command can be used with the command "."  , such as: source. BASH_RC and. The. BASH_RC is equivalent.

    3. EXEC absolute path: Exec uses the absolute path of the shell script to execute the script under the current shell (the shell is reset to the initial environment), and the shell exits when the script finishes executing.

    4. ./script starts a child shell to execute the script.

    5. Sh|bash filename starts a child shell and reads and executes the commands in the filename.

    • The child shell's variable result is not brought back to the parent shell, so use the source command when you want to set the environment variable for the current shell through a script.

shell script execution

Exec

Need to execute permissions

the script invokes the shell to execute the command actively

Fork or ./

SOURCE or .

No need to execute permissions

the Shell actively reads the script and executes

Bash or sh

When you execute a script using the SH command, you can use the-x parameter to view the execution of the script, which is useful for discovering problems when debugging scripts.

# sh-x First.sh

+ Date

Fri Jan 822:28:23 CST 2016

+ echo ' Hello world! '

Hello world!


Shell Custom Variables

Defining variables in shell scripts makes it easy for us to edit, modify, and make scripts simple.

Format: Variable name = value

Shell Mathematical Operations

When you perform mathematical operations in the shell, you need to surround them with $[].

Multiplication operations:

# a=8;b=3;echo "$a * $b =$[$a * $b]"

8*3=24

Division operation

# A=8;b=3;echo "$a/$b =$[$a/$b]"

8/3=2

    • The default shell does not support decimals. If you need decimals, you need to call BC (Calculator in Linux system) "Yum–y install BC"

    • The BC will not be rounded.

This can be done if you want to keep a 2-bit tree.

# echo "scale=2;8/ 3 "|BC

2.66


Shell user interaction

Shell scripts can be used to allow the user to enter some string (read command) or let the user choose (SELECT statement) behavior.

Read command

# Cat Read.sh

#! /bin/bash

# # Using ' read ' in shell script.

Read-p "Please input a number:" X

Read-p "Please input another number:" Y

sum=$[$x + $y]

echo "The sum of the numbers is: $sum"

The read command resembles the VisualBasic input function, which is to produce an "input line" that assigns a user-entered string to a variable after the Read command statement.

# sh read.sh

Please input a number:2

Please input another number:10

The sum of the numbers is:12

SELECT statement

The Select Loop provides an easy way to create a numbered menu from which the user can choose. It is useful when you need to select from a list and ask the user to select one or more items.

The select expression is a bash extension application that includes the following actions:

L automatically list menus with 1,2,3,4 (no echo command, automatic menu display)

L Automatic Read input selection (no read instruction, auto input)

L Assign a value to a variable (no assignment instruction, automatically enter a number, assign a string to the variable)

Syntax format:

Selectvariable in value1 value2 value3 ...

Do

Command

Done

Example:

# Cat Sel.sh

#! /bin/bash

echo "What's your favourite OS?"

Select Var in "Linux" "Gnu Hurd" "FreeBSD" "Other"

Do

Break

Done

echo "You have selected $var"

# sh sel.sh

What is your favourite OS?

1) Linux

2) Gnu Hurd

3) Free BSD

4) Other

#? 2

You have selected Gnu Hurd

    • Select itself is a loop, and break is when you choose, you jump out of the loop.

    • When the contents of a variable contain spaces, they should be enclosed in "".

Select is used in conjunction with the case statement and, in the example above, optimizes it:

# Cat Sel.sh

#! /bin/bash

echo "What's your favourite OS?"

Select Var in "Linux" "Gnu Hurd" "FreeBSD" "Other"

Do

Case $var in

Linux)

break;;

"Gnu Hurd")

break;;

"Free BSD")

break;;

Other)

break;;

*)

echo "Please enter Anumber: (1-4)";;

Esac

Done

echo "You have selected $var"

    • Select Although the loop does not display the menu after the first selection, only loops the input.

# sh sel.sh

What is your favourite OS?

1) Linux

2) Gnu Hurd

3) Free BSD

4) Other

#? 6

Please enter a number: (1-4)

#? 8

Please enter a number: (1-4)

#? 3

You have the selected free BSD

Shell Script Preset variables

# Cat Option.sh

#! /bin/bash

SUM=$[$1+$2]

echo "$0$1" + "$" = "$sum"

# SH option.sh 2 3

Option.sh 2+3=5

"$" is the name of the script itself, which is the first parameter to execute the script, which is the second parameter to execute, and $ ... Of course, there is no limit to the default variables for a shell script.


If statement

The IF statement is a logical judgment statement.

If several syntax formats:

1) If judgment statement; then Command;fi

2) If judgment statement; then Command;else Command;fi

3) If Judgment statement

Then

Command

Fi

4) If Judgment statement

Then

Command

Elif Judgment Statement

Then

Command

Else

Command

Fi

Example

# Cat If1.sh

#! /bin/bash

Read-p "Please input your score:" A

if ((a<60)); Then

echo "You didn ' tpass the exam."

Fi

Relevant content of If judgment statement

In the case of numeric relational operations, in addition to the use of (()) Form, you can also use [], but cannot use >,<,=,!= these symbols, to use-LT (less than),-GT (greater than),-le (greater than or equal),-ge (greater than or equal),-eq (equals),- NE (Not equal to).

    • When you use [], you should pay attention to the space.

Example

# Cat If1.sh

#! /bin/bash

Read-p "Please input your score:" A

If [$a –lt60]; Then

echo "You didn ' t pass theexam."

Fi

You can use && (and), | |, in a judgment statement (or),! (non)

# a=10; If [$a-lt 1] | | [$a-gt 5]; then echo OK; Fi

Ok

# a=5; If [$a-gt 1] && [$a-lt 10]; then echo OK; Fi

Ok

and file-related judgment parameters

    • -E: Determine if a file or directory exists

    • -D: Determine if the directory is not present and whether it exists

    • -F: Determine if it is a normal file and whether it exists

    • -R: Determine if the document has Read permissions

    • -W: Determine if Write permission is available

    • -X: Determine if executable

Example:

# if [-x/bin/bash]; then echo OK; Fi

Ok

# if [!–x/bin/bash];then chmod +x/bin/bash;fi

Parameters related to variables

    • -N: Determine if the variable is not empty

    • -Z: Determine if the variable is empty

    • = =: Determines whether the value of the variable is a specified value

    • ! =: Determines whether the value of a variable is not a specified value

Example:

# a=;if [-N "$a"]; Then echo ' A is not null ', else echo ' A is null '; Fi

# a=;if [-Z $a]; Then echo "A is null"; Fi

A is null

Judging a condition can also be an order

Example:

# if Grep-q ' ^mysql: '/etc/passwd;then echo ' user MySQL exitst. '; Fi

User mysqlexitst.

    • The Grep–q function is to filter but not output.

Case Selection Statement

Syntax format:

Case variable in

Value1 |value2)

Command

;;

VALUE3)

Command

;;

VALUE4)

Command

;;

*)

Command

;;

Esac

    • In the above structure, there is no limit to the number of values, you can use | to match more than one value, * represents a value other than value above.

Example:

# Cat Case.sh

#! /bin/bash

Read-p "Input a number:" N

a=$[$n%2]

Case $a in

1)

echo "The number isodd."

;;

0)

echo "The number IsEven."

;;

*)

echo "It ' s not anumber!"

;;

Esac

This is a script that judges odd even numbers, and the% is used as a sign of redundancy in the shell.

For Loop statement

The condition of the for variable name in the loop;

Command

Done

Here the "condition of the Loop" can be written as a set of strings or numbers (separated by 1 or more spaces), or it can be the result of a command, note to use anti-single quotation marks '.

# for I in 1 2 3 a B; do echo $i; Done

1

2

3

A

B

# for I in ' SEQ 1 5 '; Do echo $i;d one

1

2

3

4

5

    • SEQ command: Used to generate all integers from one number to another

# seq 1 5

1

2

3

4

5

While Loop statement

While loop statements are often used to write a dead loop script for monitoring a service.

Statement format:

While loop condition; do

Command

Done

Example:

# Cat While.sh

#! /bin/bash

A=5

While [$a-ge 1]; Do

Echo $a

a=$[$a-1]

Done

Replace the loop condition with one: (colon), which allows for a dead loop

# Cat Load.sh

#!/bin/bash

Shu=1

While:; Do

Load= ' Uptime|awk ' {print$ (NF-2)} ' |cut-d.-f1 '

If [$load-gt]&& [$shu-le 4]; then

echo "System load is high." | Mail-s "System Load" [email protected]com

shu=$[$shu +1]

Sleep 30

elif [$shu-gt 4];then

Shu=1

Sleep 3600

Else

Shu=1

Sleep 30

Fi

Done

This is a script that monitors the load of the system. No 30 seconds to detect the system load, if the load value is higher than 10 o'clock, send an alert email to [email protected], if 4 times the load is higher than 10 o'clock, then sleep 1 hours and then continue to execute the script to avoid frequent sending of messages, the administrator caused harassment (alarm convergence).

Break, continue, exit

Break: Exit this layer loop

Continue: Skip the Next statement and go directly to the next loop

Exit: Exit the current shell

#!/bin/bash
For i in ' SEQ 1 5 ';d o

Echo $i

if [$i = = 3];then break; fi
Echo $i

Done

Echo AAAAAAA

# sh break.sh

1

1

2

2

3

Aaaaaaa

#!/bin/bash
For i in ' SEQ 1 5 ';d o

Echo $i

if [$i = = 3];then continue; fi
Echo $i

Done

Echo AAAAAAA

# sh continue.sh

1

1

2

2

3

4

4

5

5

Aaaaaaa

#!/bin/bash
For i in ' SEQ 1 5 ';d o

Echo $i

if [$i = = 3];then exit; fi
Echo $i

Done

Echo AAAAAAA

# sh exit.sh

1

1

2

2

3

Shell functions

The function is to organize a piece of code into a small unit, and give the small unit a name, when the code is used, call the name of the small unit directly.

function format:

Function_name () {

Command

}

The function should be defined at the beginning of the shell script

# Cat Sum.sh

#! /bin/bash

Sum () {

Echo$1 "+" $ "=" $[$1+$2 "

}

Sum 3 4

# sh sum.sh

3+4=7

Get the IP for the NIC name:

# Cat Ip.sh

#!/bin/bash

IP () {

Ifconfig |grep-a1 "$" |tail-1 |awk ' {print $} ' |awk-f ': ' {print $} '

}

Read-p "Please input the ETH name:" E

myip= ' IP $e '

echo "$e address is $myip"

# sh ip.sh

Please input the ETH Name:lo

Lo address is 127.0.0.1

Shell Array

Defining elements:

name[Subscript]=value

ü Subscript starting from 0

To define an array:

Name= (value1value2 value3 ...)

To delete an array:

unset name

To delete an element:

unset name[Subscript]

Print all elements of an array:

Echo${name[*]} or echo ${name[@]}

    • Unlike print variables, you need to use ${} to expand the array when you print the values.

To print an array:

echo${name[Subscript]}

Print 2nd element: Echo ${a[1]}

Number of elements in the printed array:

echo${#name [@]} or echo ${#a [*]}

Array shards:

Echo${name[*]: subscript x: Subscript y}

    • Limit the array's print range and print the elements between subscript x and subscript y

Array substitution:

Echo ${name[@]/value1/value2}

    • Change the output of the array to replace value1 with value2

    • Name= (${name[@]}/value1/value2) can also be assigned in this form


Shell Scripting Tips

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.