Shell Script Programming Basics

Source: Internet
Author: User
Tags arithmetic

The shell itself is a program written in C, which is a bridge for users to use Linux. The shell is both a command language and a programming language. As a command language, it interprets and executes user-entered commands interactively, and as a programming language, it defines variables and parameters and provides many control structures in high-level languages, including loops and branches .

For the user, the shell is the most important utility, in-depth understanding and proficiency in the shell's characteristics of the extremely use of the method is the key to good Linux system.


※shell Script Basics:


※ Create shell Script

, Finally, a brief description of the update for each version


Detecting syntax errors in a script
Bash-n/path/to/some_script
Debug execution
Bash-x/path/to/some_script

※ Local Variables

Variable assignment: name= ' value '

※ Environment variables

Variable declaration, assignment: Export name=value

                declare-x name=value
       variable reference:     $name, ${name}
       Show all environment variables:
                 Env
                  PRINTENV
                 Export
                 declare-x
        Delete variable:   unset name

※ Read-only variable
ReadOnly varname
Declare-r varname
View all read-only variables
Readonly-p

※ Position Variable
Positional variables: Calling parameters passed to the script through the command line in script code
$, $, ... : corresponding to 1th and 2nd parameters, Shift [n] Change position
$: Command itself
$*: All parameters passed to the script, all parameters are combined into a string
[Email protected]: All parameters passed to the script, each parameter is a separate string
$#: The number of arguments passed to the script
[Email protected] $* only when it's wrapped in double quotes.
Set--Clears all positional variables
Note: When the position parameter reaches 10, the brackets are enlarged.

Arithmetic operations in ※bash: Help-let
+,-, *,/,% modulus (take-up), * * (exponentiation) in BC the exponentiation is ^
To implement arithmetic operations:
(1) Let var= arithmetic expression
(2) var=$[arithmetic expression]
(3) var=$ (arithmetic expression)
(4) var=$ (expr arg1 arg2 arg3 ...) Multiply to translate *, that is, \* expr $x \* $y
L
(5) declare–i var = value
(6) echo ' Arithmetic expression ' | Bc


※ Logical operation

And:
It's true and true.
True and False false
False and True
False and False false
As long as there is a false is false
If the short circuit is false with the previous one, the second value is no longer judged .

Or
It's true or true.
True or False true
False or True
False or False leave
As long as one truth is true
Short circuit or, the previous one is true, the second value is no longer judged

※ Conditional execution of the operation

Depending on the exit status, the command can be run conditionally
&& represents conditional and then
|| Represents a conditional or ELSE

Numerical test of ※bash

-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

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 for [[]], extended regular Expressions

The operands used for string comparisons should all use quotation marks

※ Exercise

1. Script/root/bin/backup.sh to enable the/etc/directory to be backed up to/root/etcyyyy-mm-dd .

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M01/9D/C4/wKioL1mFkPmDt47QAABHXSkgqXw339.png "title=" 02. PNG "style=" float:left;width:523px;height:160px; "alt=" Wkiol1mfkpmdt47qaabhxskgqxw339.png "width=" 523 "vspace=" 0 " Hspace= "0" height= "border=" 0 "/>






Resolution:-A retains all attribute permissions such as $ reference variable date +%f: Month Day


2. Write script/root/bin/sumid.sh, calculate the sum of the 10th and 20th user IDs in the/etc/passwd file

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M01/9D/C6/wKioL1mFy0Gh89HMAABAWpCEHpU447.png "title=" 03. PNG "style=" width:697px;height:70px; "alt=" Wkiol1mfy0gh89hmaabawpcehpu447.png "width=" 697 "vspace=" 0 "hspace=" 0 " height= "border=" 0 "/>

Analysis: This problem can use head and tail to intercept lines tenth and 20th, you can also use Cat-n to mark the number of lines, and then use grep to intercept the required rows, in addition to the TR and cut. But I left a space before the equals sign in the problem, so the script always went wrong. $ $ is the positional parameter.


3, scripting/root/bin/sumfile.sh, Statistics/etc,/var,/usr directory total number of sub-directories and files

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M00/9D/C6/wKioL1mFvXuSGRMvAABilZnVb28168.png "title=" 03.1. PNG "style=" width:420px;height:300px; "alt=" Wkiol1mfvxusgrmvaabilznvb28168.png "width=" 420 "vspace=" 0 "hspace=" 0 " height= "border=" 0 "/>

Parse: This problem uses the positional parameter $1,$2,$3, and the reference variable is used.


4. Write the script/root/bin/sumspace.sh, pass two file paths as parameters to the script, calculate the sum of all the blank lines in the two files.

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M01/9D/C6/wKiom1mFw_DSW8-pAAA4d71pFqM790.png "title=" 03.3. PNG "style=" width:477px;height:90px; "alt=" Wkiom1mfw_dsw8-paaa4d71pfqm790.png "width=" 477 "vspace=" 0 "hspace=" 0 " height= "" border= "0"/>

5. Script/root/bin/argsnum.sh, accept a file path as a parameter, if the number of parameters is less than 1, prompt the user "at least one parameter should be given" and immediately exit; If the number of parameters is not less than 1, the number of blank lines in the file pointed to by the first parameter is displayed

Answer:[[$ = =] "]]&& echo" should give at least one parameter "&& Exit | | Grep-c "^[[:space:]]&" $1|wc-l

Parse: This problem uses the positional parameter $; Conditional execution action: &&: Conditional and then

|| : Conditional or else


2. Write the script/root/bin/hostping.sh, accept the IPV4 address of a host as parameters, test whether it can be connected. If Ping is available, the user is prompted to "the IP address is accessible" and if it is not ping, the user is prompted "The IP address is inaccessible"

Answer:ping-c1-w1 $ &>/dev/null && echo the IP address is accessible | | echo This IP address is not accessible

Parsing:-c1: Ping only one-w1: time-out wait a second if the IP address ping can be passed to the garbage bin, if not, prompt the user.


7. Write the script/root/bin/checkdisk.sh, check the disk partition space and inode utilization, if more than 80%, the broadcast warning space will be full.

Answer: disk= ' Df|grep "/dev/sd" |sort-nr-k5|tr-s "" "%" |cut-d%-f5|head-1 '
Inode= ' Df-i|grep "/dev/sd" |sort-nr-k5|tr-s "" "%" |cut-d%-f5|head-1 '
[[$disk-GT]] && wall the disk would full| | echo the disk isn't more than 80%
[[$inode-GT]] && wall the inode would full| | echo the inode isn't more than 80%
Analysis: Compared with the above questions, the problem uses a numerical test: whether the-GT is greater than the other use of text interception tools and so on.






Shell Script Programming Basics

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.