Bash programming notes

Source: Internet
Author: User

1. What should I do with the script?
Hello. Sh
Naming, execution permission, and how to execute
2. When writing a bash script
[Root @ mail bash] # Cat hello. Sh
#! /Bin/bash
# First bash shell script
Echo "Hello world! "
Echo $
What is Echo "\ $0 ??? Indicates the Script Name "$0
Echo "\ $1 This is the script's 1st location parameter:" $1
Echo "\ $2 This is the script's 2nd location parameter:" $2
Echo "\ $3 This is the script's 3rd location parameter:" $3
Echo "\ $4 This is the script's 4th location parameter:" $4
Echo "\ $5 This is the script's 5th location parameter:" $5
Echo "\ $6 This is the script's 6th location parameter:" $6
Echo "\ $ # indicates the number of parameters in the current script position" $ #

3. Learning Condition judgment statement if
If condition
Then
Command to be executed when conditions are met
Else
Command to be executed if the condition is not true
Fi
* ****** The if keyword is followed by the "condition", and the "condition" is actually a command. If is used to determine the return value of the command and return 0, the condition is true, if the returned value is non-zero, the condition is not true.

4. the return value of the script execution is determined by the return value of the Last Command executed during the script execution.

[Root @ mail bash] # Cat checkuser. Sh
#! /Bin/bash
# Test user
If Id $1 &>/dev/null
Then
Echo "User exist"
Else
Echo "No this user"
Fi

5. Script Exception Handling
[Root @ mail bash] # Cat checkuser. Sh
#! /Bin/bash
# Test user

If test $ #-ne 1
Then
Echo "error! "
Echo "Syntax: $0 <username>"
Exit 3
Fi
If Id $1 &>/dev/null
Then
Echo "User exist"
Else
Echo "No this user"
Exit 2
Fi

6. Summary of the IF statement syntax
If condition
Then
Command
Fi
--------
If condition
Then
Command
Else
Command
Fi
-----------
If condition1
Then
Command
Elif condition2
Then
Command
Elif conndition3
Then
Command
Else
Command
Fi
------------------

7. If statement exercises
1)
[Root @ mail bash] # Cat checkfiletype. Sh
#! /Bin/bash

If! [-E $1]
then
echo $1 is not exist
Elif [-d $1]
then
echo "$1 is directory "
Elif [-L $1]
then
echo" $1 is a symbolic link "
Elif [-B $1]
then
echo "$1 is block special"
Elif test-C $1
then
echo "$1 is character special"
Elif test-p $1
then
echo "$1 is a named pipe"
Elif test-S $1
then
echo "$1 is socket file"
Elif tes T-F $1
then
echo "$1 is regular file"
else
echo "unknown"
fi
----
2)
[root @ mail bash] # Cat authuser. sh
#! /Bin/bash

If test $ #-ne 2
Then
Echo "Syntax: $0 <username> <password>"
Exit 2
Fi

# If ["$1" = "root"] & ["$2" = "123"]
If ["$1" = "root"-a "$2" = "123"]
Then
Echo "Root User auth successed"
Elif ["$1" = "PG"] & ["$2" = "123"]
Then
Echo "PG user auth successed"
Else
Echo "unknow user"
Fi

3)
[Root @ mail bash] # Cat testping. Sh
#! /Bin/bash

If Ping-C 1-W 1 $1 &>/dev/null
Then
Echo "link OK"
Else
Echo "no link"
Fi

8. Case statement, used to judge strings
Case variable name in
Value1)
Command1
;;
Value2)
Command2
;;
Value3)
Command3
;;
*)
Command4
;;
Esac

[Root @ mail bash] # Cat case. Sh
#! /Bin/bash

case "$1" in
root | PG)
echo "$1 OK"
;< br> *)
echo "fail"
;< br> esac

# Case $1 in
# Root)
# Echo "$1 OK"
#;;
# PG)
# Echo "$1 OK"
#;;
#*)
# Echo "fail"
#;;
# Esac

[Root @ mail bash] # Cat authuser_case.sh
#! /Bin/bash

Case "$1: $2" in
Root: 123)
Echo "$1 OK"
;;
PG: 123)
Echo "$1 OK"
;;
*)
Echo "unknow"
;;
Esac

++ ++
Loop

1) while statement Syntax:
N = 1
While condition # The condition written after while is the command
Do
Operations performed when conditions are met
(N ++ ))
Done
[Root @ mail bash] # cat while. Sh
#! /Bin/bash

Count = 1
While test $ count-Le 100
Do
Echo $ count
Count = $ [$ count + 1]
# (Count ++ ))
Done
# Variable Initial Value (water tank is empty), condition (water tank is not full), variable auto-increment (pick a bucket of water and make a mark, such as auto-increment 1)

[Root @ mail bash] # Cat./while2.sh
#! /Bin/bash

While:
Do
Echo "Haha"
Done

2) For statement Syntax:

[Root @ mail bash] # Cat./for1.sh
#! /Bin/bash
For (n = 1; n <= 100; n ++ ))
Do
Echo $ n
Done

[Root @ mail bash] # Cat./for2.sh
#! /Bin/bash

For N in 1 2 3 4 5 6 7 8 9 10
Do
Echo $ n
Done

For variable name in value1 value2 value3 value4
Do
Echo $ variable name
Done

 
[Root @ mail bash] # Cat for3.sh
#! /Bin/bash

For file in /*
Do
Echo $ File
Done

[Root @ mail bash] # Cat pingfor. Sh
#! /Bin/bash

For (I = 1; I <= 254; I ++ ))
Do
(If Ping-C 1-W 1 192.168.1. $ I &>/dev/null
Then
Echo 192.168.1. $ I
FI )&
Trap 'echo "received! "; Exit 0'2
Done

[Root @ mail bash] # Cat pingfor2.sh
#! /Bin/bash

For I in 'seq 1 254'
Do
If Ping-W 1-C 1 192.168.1. $ I
Then
Echo 192.168.1. $ I
Fi
Done

# For I in {1 .. 254}
# Do
# If Ping-W 1-C 1 192.168.1. $ I
# Then
# Echo 192.168.1. $ I
# Fi
# Done

[Root @ mail bash] # Cat./while3.sh
#! /Bin/bash

While:
Do
Echo 1
Sleep 3
Done
%
%
Define an array named array1
Method 1:
The elements are aa bb cc dd. There are 4 elements.
[Root @ mail bash] # array1 = (aa bb cc dd)
[Root @ mail bash] # echo ${array1 [0]} uses subscript 0 to access the first array element
AA
[Root @ mail bash] # echo ${array1 [1]} uses subscript 1 to access the second array element
Bb
To sum up, the mark of the array is to reduce the number of elements from 0 to 1.
[Root @ mail bash] # echo ${array1 [2]}
CC
[Root @ mail bash] # echo ${array1 [4]}

[Root @ mail bash] # echo ${array1 [3]}
Dd
[Root @ mail bash] # echo ${array1 [*]} displays all array elements
Aa bb cc dd
[Root @ mail bash] # echo $ {# array1 [*]} displays the number of array elements
4

Echo $ [$ {# array1 [*]}-1]
The maximum value of array array1.

Method 2:
Declare the array first, and then define the value of each element.
[Root @ mail bash] # declare-A array2 declares an array
[Root @ mail bash] # array2 [0] = aaa defines the value of the first array element
[Root @ mail bash] # array2 [1] = BBB ....
[Root @ mail bash] # array2 [2] = ccc ....
[Root @ mail bash] # array2 [3] = DDD ....
[Root @ mail bash] # echo ${array2 [*]}
Aaa bbb ccc ddd
[Root @ mail bash] # echo ${array2 [0]}
Aaa
[Root @ mail bash] # echo ${array2 [1]}
Bbb
[Root @ mail bash] # echo ${array2 [2]}
CCC
[Root @ mail bash] # echo ${array2 [3]}
Ddd
[Root @ mail bash] #

Example:

[Root @ mail bash] # Cat 100array. Sh
#! /Bin/bash

# Array100 = ('For (n = 1; n <= 100; n ++); Do echo $ random; done ')
Declare-A array1000
For (n = 0; n <= 99; n ++ ))
Do
Array1000 [$ N] = $ random
Done
Echo ${array1000 [*]}
Echo $ {# array1000 [*]}
[Root @ mail bash] #

==================== Script location parameter ================
[Root @ mail bash job 2 answer] # Set -- "1A 2a" 3A 4A 5A
[Root @ mail bash job 2 answer] # echo $1
1A 2a
[Root @ mail bash job 2 answer] # echo $2
3A
[Root @ mail bash job 2 answer] # echo $3
4A
[Root @ mail bash job 2 answer] # echo $4
5A
[Root @ mail bash job 2 answer] # echo $ #
4
[Root @ mail bash job 2 answer] # echo $ *
1A 2a 3A 4A 5A
[Root @ mail bash job 2 answer] # echo $ @
1A 2a 3A 4A 5A
[Root @ mail bash job 2 answer] # For I in "$ @"; do echo $ I; done
1A 2a
3A
4A
5A
[Root @ mail bash job 2 answer] # For I in "$ *"; do echo $ I; done
1A 2a 3A 4A 5A

Write a script to add all the location parameters of the script (the input location parameters are integers) and print the result of adding.
Method 1:
] # Cat 10.sh
#! /Bin/bash

Count = 0
# For I
For I in "$ @"
Do
Count = $ [$ count + $ I]
Done
Echo $ count
[Root @ mail bash job 2 answer] #./10.sh 1 2 3 4 5 6
21

Method 2:
] # Cat 10.sh
Count = 0
M =$ #
For (n = 1; n <= m; n ++ ))
Do
Count = $ [$ count + $1]
# Echo $1
Shift 1

Done
Echo $ count

======================== Function ====================
Purpose of defining a function: to define a functionCodeBlock to define a function name. When you want to use this code block, you can directly apply the function name without having to use this code block.

1. Define the function method as follows:
Function Name (){
Function body (code block)
}

[Root @ mail bash job 2 answer] # Cat fun1.sh
#! /Bin/bash

Myls (){
Ls
}
[Root @ mail bash job 2 answer] # Cat 10.sh
#! /Bin/bash

Total (){
Count = 0
M =$ #
For (n = 1; n <= m; n ++ ))
Do
Count = $ [$ count + $1]
Shift 1

Done
Echo $ count
}
2. Use functions:
Method 1:
Define the function directly in the script. After the definition, directly write the function name to call the function.

] # Cat 10.sh
#! /Bin/bash

Total () {here is the Function Definition
Count = 0
M =$ #
For (n = 1; n <= m; n ++ ))
Do
Count = $ [$ count + $1]
Shift 1

Done
Echo $ count
}
Total $1 $2 $3 use the function name directly

For example:
The/etc/init. d/httpd script defines start () {command1; command2 ;}
Case "$1" in
Start)
Start. Here, the function name is used to call the function.
;;
...
...
Esac

Method 2:
Define a function in one file. In another script, use the source/function file directly as a command.
For example:
Vim/etc/init. d/httpd
# Source function library.
./Etc/rc. d/init. d/functions this file defines most important system functions. The system function name is generally named after a double underline.

After the script, the status function defined in/etc/rc. d/init. d/functions is used directly.

Cancel function:
Unset-f function description
] # Unset-f Total
Cancel variable:
Unset variable name

Execution sequence: alias-Special built-in command-function-built-in command-external command

===== Bash variable operations =============
[Root @ mail test] # file = 1a. Sh defines a common variable
[Root @ mail test] # echo $ {file} print the value of a common variable
1A. Sh
[Root @ mail test] # echo $ {# file}: number of characters that print the value of a Variable
5
[Root @ mail test] # echo $ {file: 2} skips the first two characters of the Variable
. Sh
[Root @ mail test] # echo $ {file:-3} retrieves the last three characters of the Variable
. Sh
[Root @ mail test] # file =/dir1/dir2/dir3/file. Sh defines a common variable
[Root @ mail test] # echo $ {file: 6: 4} is omitted from the first six, and 4 are retrieved from the right.
Dir2

[Root @ mail test] # echo $ {file}
/Dir1/dir2/dir3/file. Sh
[Root @ mail test] # echo $ {file:-10} extract the last 10 Characters
R3/file. Sh
[Root @ mail test] # echo $ {file:-10: 3} extract the last 10 characters, count to the right, and take 3 Characters
R3/

[Root @ mail test] # echo $ {file:-3} extract the last three characters
. Sh
[Root @ mail test] # echo $ {file: 0 :$ {# file}-3}
/Dir1/dir2/dir3/File

------------ example -------------------
[root @ mail test] # ls
1A. sh 1E. sh 2D. sh 3C. sh 4B. sh 5A. sh 5E. sh
1B. sh 2a. sh 2E. sh 3D. sh 4C. sh 5B. sh
1C. sh 2B. sh 3A. sh 3E. sh 4D. sh 5C. sh
1D. sh 2C. sh 3B. sh 4A. sh 4E. sh 5D. sh
[root @ mail test] # For file in. /*; Do MV $ File $ {file: 0 :$ {# file}-3 }; done
[root @ mail test] # ls
1A 1C 1E 2B 2D 3A 3C 3E 4B 4D 5A 5C 5E
1B 1D 2a 2C 2E 3B 3D 4A 4C 4e 5B 5d

---------------------
[Root @ mail test] # echo $ {file}
/Dir1/dir2/dir3/file. Sh
[Root @ mail test] # echo $ {file % dir *} is counted from right to left to the first dir string, and all characters on the Dir and Its right are deleted.
/Dir1/dir2/
[Root @ mail test] # echo $ {file %/*} is counted from right to left to the first/string, and all the characters on the/and its right are deleted.
/Dir1/dir2/dir3
[Root @ mail test] # echo $ {file}
/Dir1/dir2/dir3/file. Sh
[Root @ mail test] # echo $ {file % I *} count from right to left to the last I string, and delete all the characters on the I and its right
/D

[Root @ mail test] # echo $ {file}
/Dir1/dir2/dir3/file. Sh
[Root @ mail test] # echo $ {file # * I} count from left to right, count to the first I character, delete all the characters on the I and its left
R1/dir2/dir3/file. Sh

[Root @ mail test] # echo $ {file # */} count from left to right, count to the last character, and delete all the characters on the/and left.
File. Sh

[Root @ mail test] # basename/dir1/dir2/dir3/file. Sh
File. Sh
----------------------
[Root @ mail test] # ls
1a.txt 1e.doc s 2d. Sh 3C. Sh 4B. Sh 5A. Sh 5E. Sh
1b. Sh 2a. Sh 2E. Sh 3D. Sh 4C. Sh 5B. Sh
1c. Sh 2B. Sh 3A. Sh 3E. Sh 4D. Sh 5C. Sh
1D. Sh 2C. Sh 3B. Sh 4A. Sh 4E. Sh 5d. Sh

[Root @ mail test] # For I in./*; Do MV $ I $ {I %. *}; done
[Root @ mail test] # ls
1A 1C 1E 2B 2D 3A 3C 3E 4B 4D 5A 5C 5E
1B 1D 2a 2C 2E 3B 3D 4A 4C 4E 5B 5D

************************
[Root @ mail test] # echo $ {file} defines a variable File
/Dir1/dir2/dir3/file. Sh
[Root @ mail test] # echo $ {file:-ABC}:-indicates that if the variable file is defined, it is still the value of the original variable. If the variable is not defined, then the ABC string is temporarily assigned to the variable file.
/Dir1/dir2/dir3/file. Sh
[Root @ mail test] # unset file cancels the variable File
[Root @ mail test] # echo $ {file:-ABC}
ABC
[Root @ mail test] # echo $ {file}

[Root @ mail test] #

:-In general, it can be equivalent-
Echo $ {file:-ABC} is equivalent to echo $ {file-ABC}
However, when file = "" is null, the following result is displayed:
[Root @ mail test] # file = ""
[Root @ mail test] # echo $ {file-"ABC"}-think the variable has been defined

[Root @ mail test] # echo $ {file:-"ABC"}:-considers that the variable is not defined, so the temporary value is assigned as a new string.
ABC

[Root @ mail test] # file =/dir1/dir2/dir3/file.txt
[Root @ mail test] # echo $ {file: + ABC} indicates that if the file is defined, the value is assigned to ABC again. If the file is not defined, it is not redefined.
ABC
[Root @ mail test] # echo $ {file}
/Dir1/dir2/dir3/file.txt

[Root @ mail test] # echo $ {file2}. For example, if the file2 variable is not defined, it is not redefined.

[Root @ mail test] # echo $ {file2: + ABC}

[Root @ mail test] #

: + In general, it can be equivalent to +
Echo $ {file: + ABC} is equivalent to echo $ {file + ABC}
However, when the file = "" value is null, it will be different.

[Root @ mail test] # echo $ {file4}

[Root @ mail test] # echo $ {file4: = ABC}: = indicates that if the variable is not defined, it is permanently assigned as the new string ABC. If the variable has been defined, hold the original value
ABC
[Root @ mail test] # echo $ {file4}
ABC
[Root @ mail test] #

[Root @ mail test] # echo ${file7 :? Is not set} indicates that if file7 is not defined, the prompt is :? String.
Bash: file7: is not set
[Root @ mail test] # file7 = "123" If file7 has been defined, no prompt is prompted.
[Root @ mail test] # echo ${file7 :? Is not set}
123

[Root @ mail PG] # echo-en "\ 033 [0; 39 m"
[Root @ mail PG] # echo-en "\ 033 [0; 33 m"
[Root @ mail PG] # echo-en "\ 033 [0; 35 m"
[Root @ mail PG] # echo-en "\ 033 [0; 36 m"
[Root @ mail PG] # echo-en "\ 033 [0; 37 m"
[Root @ mail PG] # echo-en "\ 033 [0; 38 m"
[Root @ mail PG] # echo-en "\ 033 [0; 39 m"
[Root @ mail PG] # echo-en "\ 033 [0; 40 m"

 

Source: http://www.cnblogs.com/end/archive/2012/09/25/2701915.html

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.