Shell script Programming "on"

Source: Internet
Author: User
Tags arithmetic readable egrep

Shell script Programming "on"


A program is a combination of instructions and data.


Program Programming Style:

Program: command-centric, data-serving instruction

Image: Data-centric, command-serving data


Programming Languages:

Low Level: Compilation

Senior:

Compiling: High-level language--compiler---Target code java,c#

Explanation: Advanced language--interpreter--machine code shell, Perl, Python

Shell program: Provides programming capabilities to interpret execution


A shell script is a text file that contains some commands or declarations and conforms to a certain format

The format is as follows:

First line shebang mechanism

#!/bin/bash

#!/usr/bin/python

#!/usr/bin/perl


So what are the uses of shell scripts?


Shell scripts can have:

Automating common commands

Perform system administration and troubleshooting

Create a simple application

Working with text or files


How to create a script


First step: Use a text editor to create a text file the first line must include the shell declaration sequence: #! #!/bin/bash Add comment comments start with #

Second step: Run the script to give Execute permission, specify the absolute or relative path of the script on the command line run the interpreter directly, run the script as the parameter of the Interpreter program


For example:

#!/bin/bash

#author: Wang

#Version: 1.0

#Description: This script displays some information about your


When you finish writing a script you need to check and then you can use the error-checking commands are:


1 Bash-n/path/to/some_script

Detecting syntax errors in a script

2 Bash-x/path/to/some_script

Debug execution


Variable: named memory space


Data storage: Characters: Numeric: integer, floating-point

Variable: Variable type

Functions: 1, data storage format 2, the participating Operation 3, the data range represented

Type: Character value: integer, floating-point



Based on criteria such as the scope of the variable's entry:


Local variable: The active scope is the current shell process and is not valid for Shell processes other than the current shell, including the current Shell's child shell process: The active scope is the current shell process and its child processes Local variables: The effective range is the position variable of a code fragment (usually referred to as a function) in the current shell process: $ $, $ ... To indicate that the script is used to invoke parameters passed to it through the command line in the script code.

Special variables: $?, $, $*, [email protected], $#


Local variables


Variable assignment: name= ' value ', you can use reference value:

(1) can be a direct string; Name= "Root"

(2) Variable reference: name= "$USER"

(3) Order reference: Name= ' Command ', name=$ (command)

Variable reference: ${name}, $name


1 "": weak reference, where the variable reference is replaced with the value of the variable


2 ': Strong reference, where the variable reference is not replaced with the value of the variable, while preserving the original string

Show all variables that have been defined: set

Delete variable: unset name


Environment variables


Variable declaration, assignment: Export name=value declare-x name=value

Variable reference: $name, ${name}

Show all environment variables: Export env printenv

Delete: unset name

Bash has many built-in environment variables: PATH, SHELL, Usre,uid, Histsize, HOME, PWD, Oldpwd, Histfile, PS1


Read-only and positional variables


Read-only variable: sound only, but cannot modify and delete readonly name Declare-r name position variable: Call arguments passed to script through the command line in script code

1 $, $ ... : corresponding to 1th and 2nd parameters, Shift [n] Change position

2 $: the command itself

3 $*: All parameters passed to the script, all parameters are combined into a string

4 [email protected]: All parameters passed to the script, each parameter is a separate string

5 $#: The number of arguments passed to the script

6 [email protected] $* only when it's wrapped in double quotes.

Example: Determine the number of rows given to the file linecount= "$ (wc-l $1| cut-d '-f1)" echo "has $linecount lines."


Simple arithmetic and logical operations in the shell


Arithmetic operations in BASH: Help let +,-, *,/,% modulus (take rest), * * (exponentiation)

To implement arithmetic operations:

(1) Let var= arithmetic expression

(2) var=$[arithmetic expression]

(3) var=$ (arithmetic expression)

(4) var=$ (expr arg1 arg2 arg3 ...)

(5) declare–i var = value

(6) echo ' Arithmetic expression ' | Bc

Multiplication symbols need to be escaped in some scenarios, such as * Bash has built-in random number generator: $RANDOM (1-32767) echo $[$RANDOM%50]: random number between 0-49


Logical operations


True:1

false:0

With: 1 and 1 = 1

1 and 0 = 0

0 and 1 = 0

0 and 0 = 0

Or: 1 or 1 = 1

1 or 0 = 1

0 or 1 = 1

0 or 0 = 0


Non -:!

! 1 = 0

! 0 = 1

Short-circuit Operation:

Short circuit and: The first is 0, the result must be 0, the first is 1, the second must participate in the operation;

Short circuit or: the first one is 1, the result must be 1, the first is 0, the second must be involved in the operation;

XOR: ^ xor two values, same as false, different for true



Assign value


Enhanced Assignment: + =,-=, *=,/=,%=


Let Varopervalue

Example: let count+=3 self-assignment after adding 3

Self-increment, self-reduction:

Let Var+=1

Let var++

Let Var-=1

Let var-


Gather command


There are two ways to gather commands:

Compound: date;  W.H.O. | The WC-L command will run one after another,

Child Shell: (date; W.H.O. | WC-L) >>/tmp/trace all outputs are sent to a single stdout and stderr


Exit status


Process uses exit status to report success or failure

0 stands for Success, 1-255 for failure

$? Variable saves the most recent command exit status


For example: $ ping-c1-w1 hostdown &>/dev/null $ echo $?


Condition test


To determine whether a demand is satisfied, it needs to be realized by testing mechanism;

A dedicated test expression needs to be assisted by a test command to complete the test process;

Evaluates a Boolean declaration for use in conditional execution if true, returns 0 if False, returns 1

Testing command: Test expression [expression] [[expression]] Note: There must be a white space character before and after EXPRESSION


Conditional execution operators in the shell


Depending on the exit status, the command can be run conditionally

1 && representing conditional and then

2 | | Represents a conditional or ELSE

For example: $ grep-q no_such_user/etc/passwd \ | | Echo ' No such user ' no such user $

PING-C1-W2 station1 &>/dev/null \ > && echo "station1 is up" \ > | | (Echo ' station1 is unreachable '; exit 1) Station1 was up




Test command

Example of long format: $ test "$A" = = "$B" && echo "Strings is equal" $ test "$A"-eq "$B" \ && echo "Integers is equal "

Example of shorthand format: $ ["$A" = = "$B"] && echo "Strings is equal" $ ["$A"-eq "$B"] && echo "Integers is equal"


The test types for bash are:

1 Numerical Tests

2 string test

3 Presence Testing

4 File Permission test

5 File Size Test

6 Binocular Test

Numerical test:

-GT: Is it greater than;

-ge: is greater than or equal to;

-eq: Is it equal to;

-ne: is not equal to;

-LT: Is it less than;

-le: is less than or equal to;


String test:

= =: whether equal;

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 in [[]];

-Z "string": whether the string is empty, empty is true, not empty is false

-N "string": whether the string is not empty, not empty is true, empty is false

Note: The operands used for string comparisons should all use quotation marks



Presence Testing

-a FILE: Same-E

-E File: The existence of the test, the existence of the true, otherwise false;

Presence and category Testing

-B File: Whether it exists and is a block of device files;

-C File: Existence and character device files;

-D file: exist and are directory files;

-F file: exists and is a normal file;

-H file or-L file: exists and is a symbolic link;

-P file: exists and is a named pipe file;

-S file: exists and is a socket file;


File permission test:

-R FILE: exists and is readable

-W FILE: exists and is writable

-X FILE: exists and is executable


File Special Permissions Test:

-G FILE: Exists and has sgid permissions;

-U FILE: Exists and has suid permissions;

-K FILE: Exists and has sticky permissions


File size test:


-S file: exists and is not empty; file is open:

-T FD:FD indicates whether the file descriptor is open and related to a terminal-N file: Whether the file has been modified since it was read automatically

-O File: Whether the current active user is a file owner

-G file: whether the current active user is a group of files


Binocular test:

File1-ef whether File2:file1 and FILE2 point to the same inode on the same device

Whether File1-nt File2:file1 is new to FILE2;

File1-ot File2:file1 is older than FILE2;


Combination test conditions


First way: COMMAND1 && COMMAND2 and COMMAND1 | | COMMAND2 or! COMMAND not: [-e file] && [-R File]

The second way: Expression1-a EXPRESSION2 and Expression1-o EXPRESSION2 or! EXPRESSION


Must be performed using a test command; # [-Z ' $HOSTNAME "-o $HOSTNAME" ==\ "Localhost.localdomain"] && HOSTNAME www.magedu.com # [-f/bin/ Cat-a-x/bin/cat] && cat/etc/fstab


Use with the Read command


Use read to assign the input value to one or more shell variables:

-p Specifies the prompt to display

-T TIMEOUT read reads values from standard input, assigns a variable to each word all remaining words are assigned to the last variable


Read-p "Enter a filename:" FILE



Exercises


1, write script/root/bin/systeminfo.sh, display the current host system information, including host name, IPV4 address, operating system version, kernel version, CPU model, memory size, hard disk size.


#!/bin/bash

#descrition: Show some information about hostname ipv4address version kernel CPU disk and memory

Hostname= ' Hostname '

ipv4= ' Ifconfig | Sed-n ' 2p ' |sed-r ' s#.*addr: (. *). *b.*#\1# '

version= ' Cat/etc/redhat-release '

Kernel= ' Uname-r '

cpu= ' Lscpu | Sed-n '/^model name.*/p ' |sed-r ' [email protected]*[[:space:]]{3}+ (. *$) @\[email protected] "

memory= ' free-h |tr-s "" |cut-d ""-f2 | Sed-n ' 2p '

disk= ' fdisk-l |sed-n ' 2p ' | Sed-r ' [Email protected]* (. *) Gb.*@\[email protected] "

Echo ' hostname: ' $Hostname

Echo ' IPv4: ' $IPV 4

Echo ' OS version: ' $version

Echo ' Kernel: ' $kernel

Echo ' CPU: ' $Cpu

echo ' Memory: ' $memory

echo "Disk: $disk"




2, scripting/root/bin/backup.sh, can be implemented daily/etc/directory backup to/root/etcyyyy-mm-dd


#!/bin/bash

#descrition: Copy

Echo ' copy/etc .... '

Cp-a/etc/root/${date +%f}

Echo ' Copy is over '

[Email protected] bin]# bash backup.sh

Copy/etc ....

Copy is Over



3, Write script/root/bin/disk.sh, display the current hard disk partition of the maximum space utilization value,


#!/bin/bash

#show the Using max rate on disk

max= ' df |tr-s '% ' |cut-d '% '-f5|sort-n |tail-1 '

echo "Maxrate: $max"

[Email protected] bin]# bash disk.sh

Maxrate:47



4. Write Script/root/bin/links.sh, show the IPV4 address and connection number of each remote host connecting to this host, and sort by the number of connections from large to small


#!/bin/bash

#show the Links

links= ' netstat-nt |tr-s ' |tail-n +3 | Cut-d ""-f5 | Sed-r ' [email protected] (. *):. *@\[email protected] ' |sort |uniq-c '

echo "$links"

[Email protected] bin]# bash link.sh

1 10.1.25.29



5, write a script/root/bin/sumid.sh, calculate the/etc/passwd file of the 10th user and the 20th user ID of the sum


#!/bin/bash

#descrition: Sumid

Sumid= ' sed-n ' 10p;20p '/etc/passwd|cut-d:-f 3 |tr ' \ n ' + ' | Sed-r ' s# (. *) \+#\1\n# ' | BC '

echo "Sumid: $sumid"

[Email protected] bin]# bash sumid.sh

Sumid:80




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


##!/bin/bash

#descrition: Sum about space

space1= ' grep ' ^$ ' $ | Wc-l '

Space2= ' grep ' ^$ ' $ | Wc-l '

Sumspace= $space 1+ $space 2

echo "Sumspace: $Sumspace"

[Email protected] bin]# bash sumspace.sh/etc/rc.d/init.d/functions. /.bash_profile

sumspace:109



7, write a script/root/bin/sumfile.sh, statistics/etc,/var,/usr directory total number of sub-directories and files


#!/bin/bash

#descrition: Sum about directory

Etcnum= ' ls-a -1/etc/|wc-l '

Varnum= ' ls-a -1/var/|wc-l '

Usernum= ' ls-a -1/usr/|wc-l '

sum= $etcnum + $varnum + $usernum

Sum: $sum "

[Email protected] bin]# bash sumfile.sh

sum:299



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


#!/bin/bash

#

[[$#-lt 1]] && echo "Enter at least one parameter" | | (grep ' ^$ ' | wc-l)

[Email protected] bin]# bash argsnum.sh/etc/rc.d/init.d/functions

105

[Email protected] bin]# bash argsnum.sh

Enter at least one parameter




9, write a script/root/bin/hostping.sh, accept a host's IPv4 address 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"


#!/bin/bash

#descrition: How to Ping

Ping-w1-c1 "$" &>/dev/null

Ping= ' echo $? '

[[$Ping-eq 0]] && (echo "The IP address is accessible") | | (echo "The IP address is not accessible")

[Email protected] bin]# bash hostping.sh 10.1.25.29

The IP address can be accessed

[Email protected] bin]# bash hostping.sh 10.1.25.155

The IP address is not accessible




10, Chmod-rw/tmp/file1, write script/root/bin/per.sh, determine whether the current user/tmp/fiile1 file is not readable and not writable


#!/bin/bash

#

([!-r/tmp/flie1]) && ([-w/tmp/file1]) && (echo "This user is not read/write to/tmp/file1 files")


11, write scripts/root/bin/nologin.sh and login.sh, implement prohibit and allow ordinary user login system.


#!/bin/bash

#descrition: Nologin and Login

[-f/etc/nologin] && (echo "Normal user can not login") | | (Touch/etc/nologin)



12.

Write a script/root/bin/hostping.sh, accept a host of the IPV4 address as a parameter, first determine whether the qualified IP, no, prompt IP format is not legal and exit, is,

Test whether connectivity is possible. 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"


#!/bin/bash

#descrition: Check IP

echo $ | Egrep-o ' ([0-9]| ( [1-9] [0-9]) | (1[0-9]{2}) | (2[0-4][0-9]) | (25[0-5])) \. ([0-9]| ([1-9][0-9]) | (1[0-9]{2}) | (2[0-4][0-9]) | (25[0-5])) \. ([0-9]| ([1-9][0-9]) | (1[0-9]{2}) | (2[0-4][0-9]) | (25[0-5])) \. ([0-9]| ([1-9][0-9]) | (1[0-9]{2}) | (2[0-4][0-9]) | (25[0-5])) \> ' &>/dev/null

Result= ' echo $? '

[Result-ne 0] && echo "It not IP" && exit 222

Ping-w1-c1 "$" &>/dev/null && (echo "Can access this IP") | | (echo "You can not access this IP")



13, calculate the value of 1+2+3+...+100


[Email protected] ~]# Seq-s + 1 |BC

5050




14. Calculate the sum of all the numbers from the first parameter a of the script, to the second parameter B, to determine if B is greater than a, to indicate the error, and to exit.


#!/bin/bash

#计算从脚本第一参数A开始, to the sum of all the numbers in the second parameter B, to determine whether B is greater than a, whether to prompt for errors and exit, is the calculation

[$2-GT] && (seq-s + $ | egrep-o '. *[^+] ' |bc) | | (echo "The number is wrong")


[[email protected] bin]# Bash numa_b.sh 1 100

5050


Shell script Programming "on"

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.