Shell Third: basic syntax

Source: Internet
Author: User
Tags arithmetic arithmetic operators case statement function definition

Directory one, what is shell script two, variable three, operator four, flow control five, function

   first, what is shell script

Stacking OS commands into executables, executing the OS commands in the text from top to bottom, is scripting, and with some intelligent (conditional/control) controls, it becomes an intelligent script.

 

second, the variable

Why do part1 have variables

The operation of a program is a variable of some column state, which is represented by the change of variable value.

Part2 Variable Naming conventions

Start with a letter or underscore, and the rest can be: letters, numbers, underscores

It is advisable to follow the following rules:

1. Start with a letter

2. Use the underline or underline to make the word link

3, the same type of the best use of numbers to distinguish

4, for the file best plus extension

Example: sql_bak.tar.gz,log_bak.tar.bz2

PART3 System Variables

Set and env differences

Set: Show All variables

ENV: Environment variables

Part4 variable Assignment

Varname=value

Echo $VARNAME
Delete variable unset VARNAME

Part5 Common system Variables

PATH

Pwd

Lang

HOME

Histsize

PS1

Ifs

The area separator is a space, wrap, TAB key collection

PART6 global variables and local variables

[Email protected] ~]# gender= ' Male ' #在爹这个位置定义一个局部变量gender

[Email protected]srv ~]# Export money=1000 #在爹这个位置定义一个全局变量money
[Email protected] ~]#
[Email protected] ~]#
[Email protected] ~]# bash #切换到子bash
[[email protected] ~]# echo $gender #在儿子这里看它爹的局部变量gender, results are empty, not seen

[[email protected] ~]# echo $money #在儿子这里看它爹的全局变量money, you can see
1000
[Email protected] ~]#
[Email protected] ~]# export hobby= ' Piao ' #在儿子这里定义一个全局变量hobby
[[Email protected] ~]# exit #退出, go into Dad's bash environment
Exit
[Email protected] ~]# echo $hobby #爹是看不到儿子的export的, son's son can see

[Email protected] ~]#

Part7 defining the bounds of variable names

[Email protected] ~]# rest_mem=20
[Email protected] ~]# echo ${rest_mem}%
20%

PART8 Data types

The variables in bash do not need to be declared, they can be used directly, the default variables are character types, there can be numeric types, and normal scripts, both of which are sufficient.

third, operator


Part1 Arithmetic operators

+ 、-、 *,/,%

PRAT2 Relationship Operations

with (()), <, >, <=, >=, = =,! = , &&, | |

Test command related, [] can achieve the same effect

[Email protected] ~]# x=1

[Email protected] ~]# [$x-gt 1]
[[email protected] ~]# echo $?
0

Part3 assignment operator

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

[Email protected] ~]# x=10
[Email protected] ~]# ((x%3))
[Email protected] ~]# echo $x
10
[Email protected] ~]#
[Email protected] ~]# ((x%=3))
[Email protected] ~]# echo $x
1

Part4 all the calculators in the shell

$[] (()) $ (()) expr BC Bc-l

Floating point arithmetic: Yum install bc-y

[Email protected] ~]# echo ' SCALE=2;1/3 ' |bc-l
.33

PART5 Test actions

When the command executes, it returns to a system variable of $?

A value of 0 indicates that the command executed successfully, otherwise it failed

  

Test command text[][[]] (())

Open man test to introduce each parameter

1. test file status

-D Directory

-S file length > 0, non-empty

-F Regular File

-W Writable

-R Readable

-X Executable

-L Symbolic Link

-U files have a suid location

2. String test

= Two strings added

! = two strings are not equal

-Z Empty string

-N Non-empty string

[[email protected] ~]# var1= ' abc '
[[email protected] ~]# var2= ' 123 '
[[Email protected] ~]# [$var 1 = = $var 2]
[[email protected] ~]# echo $?
1

3. Test value

-ep equals

-ne Not equal to

-GT Greater than

-lt less than

-ge greater than or equal to

-le less than or equal to

[Email protected] ~]# [10000-GT] #不要使用大于号小于号等于号等, to use the man test specified, see the next section 4 expand
[[email protected] ~]# echo $?
0

4, expand the test symbol

Digital Test Symbols

# < 2] # syntax error
-bash:2: No file or directory


# [[2 > 10]] # result Error
# echo $?
  0
# [[> 10]] # correct
# echo $?
  0
# (<)
# echo $?
0

Character test
# ["AA" = "AA"]
# echo $?
0
# [["AA" = "AA"]]
# echo $?
0
# (("AA" = "AA")) #结果错误
# echo $?
1
Hybrid testing
# [A = A-a < 20]
-BASH:20: No file or directory
[[Email protected] ~]# [[a = A-a < 20]]
-bash:syntax Error in conditional expression
-bash:syntax error near '-a '
[[Email protected] ~]# [[a = a && < 20]]
[[email protected] ~]# echo $?
0
[[Email protected] ~]# [[a = a | | < 20]]
[[email protected] ~]# echo $?
0
[[Email protected] ~]# ((a = a | | < 20))
[[email protected] ~]# echo $?
0
[[Email protected] ~]# ((a = a && < 20))
[[email protected] ~]# echo $?
0
[Email protected] ~]#
  

Iv. Process Control

PART1 Branching structure

  

#!/bin/bashvar= '/etc/init.d ' #var = '/dev/sda ' If [-D $var] then        echo "$var is directory" Elif [-B $var]    then< C3/>echo "$var is block" elif [-F $var] then        echo "$var is regular file" Else        echo ' Unknow ' fi

The if test can also execute a command based on the return value of the command to judge
# if CD/; then echo Y; fi
# if Grep-q root/etc/passwd; then echo Y; fi

  

#!/bin/Bashusername='Egon'Password='123'Read-P'User:'name Read-P'passwd:'passwdif[$name = $username-a $passwd =$password];then Echo'Login Successful'ElseEcho'username or password err'fi

  

#!/bin/Bashage= theRead-P'Num:'Nif[$n-eq $age];then echo'You get it'Elif [$n-GT $age];then Echo'too Big'Elif [$n-LT $age];then Echo'too small'fi

  

#!/bin/Bashread-P'Your score:'scoreif[$score-ge -];then Echo'Excellent'Elif [$score-ge --A $score-lt -];then Echo'Good'Elif [$score-ge --A $score-lt -];then Echo'General'Elif [$score-lt -];then Echo'Poor'fi

Passing parameters to a script

  

#test. Shecho $0echo $1echo $2echo $3echo ${11}echo ' $$ ' $ $echo ' $* ' $*echo ' [email protected] ' [email protected]echo ' $# ' $ #echo ' $? ' $? ' Test: Python test.sh 1 2 3 4 5 6 7 8 9 10 11 output:./test.sh211$$ 14312$* 1 2 3 4 5 6 7 8 9 11[email protected] 1 2 3 4 5 6 7 8 9 10 11$# 11$? 0 ""

Modify the script so that it can receive the arguments from the caller

  

[email protected] ~]# cat test_file.sh #!/bin/bashif [-D $]    then        echo ' is directory ' elif [-B $]    Then        echo "is block" elif [-F $]    then        echo "$ is regular file" Else        echo ' unknown ' fi[[email protected] ~] #./TEST_FILE.SH/ETC/PASSWD/ETC/PASSWD is regular file

PART2 Cycle Structure

While loop

while (condition)

Do

Action

Done

When an infinite loop is required, the while is selected

  

[email protected] ~]# cat login.sh #!/bin/bashwhile:d o    read-p ' please input your name: ' Name    read-p ' Nput your password: ' pwd    if [$name = ' Egon '] && [$pwd = ' 123 ']        then            echo ' login sucessful '            BR Eak #continue    fidone[[email protected] ~]#./login.sh Please input your name:egonplease input your

[email protected] ~]# cat 1.sh #!/bin/bashi=1while ((i<10)) do    echo $i    ((i++)) Done[[email protected] ~]#./1. SH 2468

While Dead loop

  

[email protected] ~]# cat 1.sh #!/bin/bashvar1=aaavar2=bbbvar3=cccwhile:d o    clear    echo-e "a:${var1}\nb:${ VAR2}\NC:${VAR3} "    temp= $var 1    var1= $var 2    var2= $var 3    var3= $temp    sleep 1done

Wihle and read implement progressive processing

  

[[email protected] ~]# cat 1.sh #!/bin/bashwhile read Vardo    echo $ ((++i)): $vardone </etc/passwd[[email protected] ~]#./1.sh 1:root:x:0:0:root:/root:/bin/bash2:bin:x:1:1:bin:/bin:/sbin/nologin3:daemon:x:2:2:daemon:/sbin:/sbin/ Nologin4:adm:x:3:4:adm:/var/adm:/sbin/nologin ......

For loop

Shell format for loop

  

For i in {1..10}doecho $idone

Shell for, common in list mode

  

For I in 1 2 3for i in {1,2,3}for i in {1..9}for i} {9..1}for I in {a]. Z}for i in {A.. Z}for i in {X.. Z}for i in $ (cmd) for I in $ (find ...)

Example:

  

Check the intranet for surviving IP    #!/bin/bash for    i in {1..254} do            (ping-w 1-c 1 192.168.1. $i &>/dev/null && Ech o 192.168.1. $i) &    done            allows file test scripts to support multiple parameters    #!/bin/bash for i in        [email protected] do      if [[-D $i] ]      then        Echo, "$i is directory."      elif [[-B $i  ]] then        echo "$i is block device."      Elif [-F $i] then        echo "$i is a regular file."      else        echo "Unknow."      Fi done    

Multiple for nesting

Nested for in use

Continue: Exit this loop by default

Break: Exit this layer loop by default

  

Using the Break:break default parameter is 1 so write break equals break 1 meaning: Exit the current loop layer break 2 then exit the 2 layer loop now the current loop is also computed in the exit hierarchy for I in {1..9}dofor J in {0..9} dofor N in {0..9}doecho $i $j$nif ((n==5)) Thenbreak 3fidonedonedone Using continuecontinue = Continue 1 in the secondary loop, ignoring continue subsequent code is: Immediately ends the current cycle in the loop, and into the next loop of the current loop continue 2 = break 1continue 3 = Break 2 .... And so on, for I in {1..9}dofor j in {0..9}dofor N. {0. .9}doecho $i $j$nif ((n==5)) Thencontinueecho "-----------------------------" Fidonedonedone

You can write a for loop directly at the command line

# for I in {1..10};d o [$i-eq 5] && Continue | | Echo $i;d One
# for I in {1..10};d o [$i-eq 5] && Break | | Echo $i;d One

  

Practice:
Count the number of each type of file in/dev

  

#!/bin/bashdir= '/dev ' for i in ' ls $dir ' do    if [-B $dir/$i] then        ((block++))    elif [-F $dir/$i]    then< c5/> ((file++))             elif [-D $dir/$i] then        (directory++))    Else        ((unkown++))    Fidoneecho ' Block ' $blockecho ' regular file ' $fileecho ' directory ' $directoryecho ' unkown ' $unkown

Pass a user name to the script to verify that the user exists

  

[[email protected] ~]# cat testuser.sh #!/bin/bashid $ &>/dev/nullif [$?-eq 0];then    echo "User exists" Else
   echo "User $ not present" Fi[[email protected] ~]#./testuser.sh Root User root exists

Add 30 users, and then delete them

  

For i in {1..30};d o    useradd user$i&&echo "user$i Create successful" Donefor I in {1..30};d o    userdel-r user $i &&echo "user$i Delete successful" done

PART3 Case Statement

  

Read-p "Username:"-T 5 uname
Echo
if [[-Z $uname]]
Then
Uname=default
Fi

Case $uname in
Root
echo "Welcome $uname"
;;
Seker)
echo "Welcome $uname"
;;
Default
echo "Welcome $uname"
;;
*)
echo "No user $uname"
Esac

Part4 combine to create a simple menu function

  

#!/bin/bashecho "script name: ' basename $ '" echo "version 1.0" echo "Date 2017-03-23" echo "Author:biubiu" while Read-p "(H to help):" Vardo case $var in p| p|cpu| CPU) echo-e "\ n" grep ' model name\|cpu mhz\|processor '/proc/cpuinfo |sort |uniq Echo        -E "\ n";; m|m|mem|        MEM) echo-e "\ n" free echo-e "\ n";; d| d|disk|        DISK) echo-e "\ n" df-th echo-e "\ n";; h| h|help| Help) Echo-e "\n\tcommand\taction\n\n" for I in the CPU mem disk do ECHO-E "\t$i            \t${i}_info "Done echo-e" \thelp\tthis help page: "            Echo-e "\tquit\texit!!.."        Echo-e "\ n";; q|        Q|quit|exit) exit;; *) echo-e "\n$var Enter error...\n" Esacdone 

Additional:

  

# cat select.sh #!/bin/bashps3= ' Choose one: ' #select default to use PS3 to do a prompt echoselect var in $ (for I in {A). D};d o echo $i;d one) Doechoecho "Your choose is $var" echo "OK" Echobreak # jump out of SELECT, otherwise dead Loop done# #./select.sh1) A2) B3) C4) D Choose One:3your Choose is cok# if omitted in list then [email protected] Do List item # Cat select.sh #!/bin/bashps3= ' Choose one: ' Echosele CT var Doechoecho "Your choose is $var" echo "OK" echobreakdone##./select.sh A B C D1) A2) B3) C4) dchoose One:cyour Choos E is OK learn: Select menu

Five, function

Functions in the interactive shell

Function abc () {echo ' AAA '; Echo ' bbbb ';}

Set view

Call ABC

  

[email protected] ~]# ABC
Aaa
bbbb
[Email protected] ~]#


Functions in the script

1. Function definition
The shell allows a set of command sets or statements to form an available block called a shell function
Define the format of the function:

Function-name () {
Command1
........
}
or function Function-name () {#函数名前面多了个function关键字
Command1
........
}
2. Function calls
The following is a script instance of a function:
#!/bin/bash
#hello
function Hello () {#声明函数
echo "hello!" #函数的主体, Output "hello!"
} #函数结束
Hello #调用函数
3. Parameter passing
Passing arguments to a function is like using a variable location in a script $1,$2,$3...$9
The following is an instance of a passing parameter:
#!/bin/bash
#hellofun
function Hello () {
echo "hello! The first parameter is ' $ '.
}
Hello good
#该脚本执行的结果是: hello! The first parameter is ' good '.
4. function files
Save the file of the function, write a function file with the above example as follows:
#!/bin/bash
#hellofunction
function Hello () {
echo "Hello!"
Return 1
}
The Hellofunction file above is a function file that can be called from another script
#!/bin/bash
#hellof
. Hellofunction #注意点和hellofunction之间有个空格
Hello
5. Loading and deleting
To view loaded functions with Set
Cancel loading with unset function-name
Examples are as follows:
#!/bin/bash
#hellof
. Hellofunction
unset Hello
Hello #因为已经取消载入: So it goes wrong.
6. function return Status
#!/bin/bash
#hellofun
function Hello () {
echo "hello! The first parameter is ' $ '.
Return 1
}
Hello
echo $? #输出返回的状态值 (General success is return 0, other values are failed)

Shell Third: basic syntax

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.