Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Theory: learn shell programming specifications and variables in detail-A beginner must point in to explain the theory

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Foreword:

Shell script programming specification shell script application scenario shell programming specification pipeline and redirection shell script variables reveal custom variables special variables

In this study, we understand variables.

Languages are divided into two categories.

1. Strong language: data types need to be declared when defining variables. Once declared, the jave c language is immutable.

1 integer init 1 2 3 100

Long integer long

2 floating point single precision float 4 bytes

Double precision double 8 bytes

Floating point with decimal point

3.string string

Char character English alphabet character an occupies one byte

​ Chinese characters, male occupies two bytes

In java, all characters occupy two bytes

4 boolean Boolean values ture and false

5 date date

Int await 10; a

Weak language: shell javascript python does not need to declare

Axi10

Axiom 10.1

You can give any meaning to a.

Html markup language exists in the form of tags

Xml file format

Json key: value key:value aRom 10

Advantages of shell:

​ variables are defined directly, without declaration, without object-oriented thinking, and all languages are written like a ledger.

Array function

1: shell script Overview 1.1 the concept of shell script commands to be executed are sequentially saved to a text file to give the file executable permissions, easy to run + an x execution authority can be combined with various shell control statements to complete more complex operations 1.2 shell scripts application scenarios repetitive operations batch transaction processing automation operation management server running status monitoring scheduled task execution

First of all, you should memorize the commands and sentences.

Second: the role of shell 2.1The role of shell-- the command interpreter, the "translator" is between the kernel and the user, and is responsible for interpreting the command line.

2.2 user's login shell program used by default after shell login Generally speaking, the internal commands and running environments of different shell are different for / bin/bash [root@localhost ~] # cat / etc/shells/bin/sh'/bin/bash'/sbin/nologin/usr/bin/sh/usr/bin/bash/usr/sbin/nologin/bin/tcsh/bin/csh [root@localhost ~] # III: write the first shell script 3.1 write script code with one Linux command per line in the vi text editor Write the inherent format of the t@localhost ~] # vi frist.shroud script in order of execution:'cd / boot/pwdls-lh vml* [root@localhost] # chmod 744 frist.sh [root@localhost ~] #. / frist.sh / boot-rwxr-xr-x. 1 root root 5.7m October 23 13:40 vmlinuz-0-rescue-33c124456fa34c50a98483245dfea58d-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x86_64

To indicate the end of a sentence, you can use a semicolon to use two commands at the same time

[root@localhost boot] # ls Who 'commands are separated by semicolons to execute two commands' config-3.10.0-693.el7.x86_64efigrubgrub2initramfs-0-rescue-33c124456fa34c50a98483245dfea58d.imginitramfs-3.10.0-693.el7.x86_64.imginitrd-plymouth.imgsymvers-3.10.0-693.el7.x86_64.gzSystem.map-3.10.0-693.el7.x86_64vmlinuz-0-rescue-33c124456fa34c50a98483245dfea58dvmlinuz-3.10.0-693.el7.x86_64root at the same time. 0 0-11-25 13:43 (: 0) root pts/0 2019-11-25 17:06 (: 0) 17:06 execute script file. / method 1: script file path (absolute path and relative path) [root@localhost] #. / frist.sh method 2: sh script file path [root@localhost ~] # sh frist.sh / boot-rwxr-xr-x. 1 root root 5.7m October 23 13:40 vmlinuz-0-rescue-33c124456fa34c50a98483245dfea58d-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x86_64 [root@localhost] # method 3: source script file path [root@localhost] # source frist.sh / boot-rwxr-xr-x. 1 root root 5.7m October 23 13:40 vmlinuz-0-rescue-33c124456fa34c50a98483245dfea58d-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x86_64 [root@localhost boot] #

. / the file for this method must have execute x permission

Sh execution, the current path remains unchanged

Source execution, the current path has been changed

3.3 better script composition script declaration comment information executable statement [root@localhost ~] # vim frist.sh #! / bin/bash#this is my frist shell-script.cd / boot/echo "current directory is located in:" 'output friendly message' pwdecho "where files starting with vml include:" ls-lh vml*~ "

Echo stands for output statement, and the output string is in double quotation marks

[root@localhost ~] #. / frist.sh is currently located in: / boot, where files starting with vml include:-rwxr-xr-x. 1 root root 5.7m October 23 13:40 vmlinuz-0-rescue-33c124456fa34c50a98483245dfea58d-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x8664 IV: redirect and pipe operation 4.1 Interactive hardware device 01 2 standard input: accept user input data standard output: output data standard error: report execution error information through the device

4.2 redirect operation >

Redirect symbols can be used to write log files

[root@localhost ~] # chattr + I / etc/passwd 'lock account file' [root@localhost ~] # lsattr / etc/passwd 'View shackles'-I-/ etc/passwd [root@localhost ~] # useradd zhaoyun 'Test' useradd: unable to open / etc/passwd 'standard error output' [root@localhost ~] # useradd zhaoyun 2 > err.txt 'use 2 > redirect' [root@localhost ~] # lsanaconda-ks.cfg frist.sh test.sh template picture download desktop err.txt initial-setup-ks.cfg public video document music [root@localhost ~] # cat err.txt 'View' useradd: unable to open / etc/passwd4.3 pipe operation symbol "|" output the command on the left As the processing object of the command on the right, 'cmd1 | cmd2 [. | cmdn] [root@localhost ~] # grep "bash$" / etc/passwdroot:x:0:0:root:/root:/bin/bashgsy:x:1000:1000:gsy:/home/gsy:/bin/bash [root@localhost ~] # grep "bash$" / etc/passwd | awk-F:' {print $1J 'root / bin/bashgsy / bin/bash [root@localhost ~] #

Regular expression three Musketeers

Grep egrep boss filter keywords

Sed number two reads by line

The third awk reads data according to the column.

Awk-F specifies that if the delimiter is not added with-F, the default delimiter is a tab or space

'{print prints $1 first parameter $7 seventh parameter}'

$1 $2 represents a location variable

[root@localhost ~] # df-Th file system type capacity available available mount point / dev/mapper/centos-root xfs 20g 7.6g 13g 38% / devtmpfs devtmpfs 977M 0977m 0% / devtmpfs tmpfs 993M 0993M 0% / dev/shmtmpfs Tmpfs 993M 9.0M 984m 1% / runtmpfs tmpfs 993M 0 993M 0% / sys/fs/cgroup/dev/sda1 xfs 6.0G 161m 5.9G 3% / boot/dev/mapper/centos-home xfs 10G 37M 10G 1% / hometmpfs tmpfs 199M 20K 199m 1% / run/user/0/dev / sr0 iso9660 4.3G 4.3G 0% / run/media/root/CentOS 7 x86room64 [root@localhost ~] # df-Th | awk'{print $1 The file system type has been used% / dev/mapper/centos-root xfs 38%devtmpfs devtmpfs 0%tmpfs tmpfs 0%tmpfs tmpfs 1%tmpfs tmpfs 0%/dev/sda1 xfs 3%/dev/mapper/centos-home xfs 1%tmpfs tmpfs 1%/dev/sr0 iso9660 5: the function of shell variable and type 5.1 variable provide specific parameters for flexible management of limux system There are two meanings of variable names: using a fixed name, system preset or user-defined variable values: types of custom variables that can be changed according to user settings and changes in the system environment: user-defined, modified and used environment variables: maintained by the system, used to set working environment location variables: pass parameters to scripts through the command line predefined variables: a class of variables built into Bash You cannot directly modify 5.2 to define a new variable-- Custom variable = echo

Variable names begin with subtitles or underscores and are case-sensitive. Full uppercase is recommended.

Variable name = variable value

View the value of a variable

Echo $variable name [root@localhost ~] # addr=192.168.100.100 [root@localhost ~] # echo $addr192.168.100.100 [root@localhost ~] # addr=10 [root@localhost ~] # echo $addr10 [root@localhost] # num=$addr [root@localhost ~] # addr=20 [root@localhost ~] # echo $addr $num20 10 [root@localhost ~] # product=puthon [root@localhost ~] # version=3.7 [root@localhost ~] # echo $product $versionputhon 3.7 [root@localhost ~] # echo $product2.8 'when a variable name is connected to a number Do not show'.8 [root@localhost ~] # echo $product 2.8puthon 2.8[ root@localhost ~] # [root@localhost ~] # echo ${product} 2.8' if the desired result is connected with the number, you need to use the {} symbol 'puthon2.8.

The = sign is an assignment symbol that assigns the value on the right to the value on the left

Addr= "192.168.100.100"

_ abc= "hello"

Variables cannot begin with numbers and Chinese characters, they can only be letters or underscores

The naming method of java is called Xiamei Camel.

Camel is the name of camel.

When you output, precede the variable with a $symbol

Variable assignment is equivalent to opening up a storage space in memory, putting the given value in the space.

5.3 use quotation marks when assigning values: allow references to other variable values through the $symbol, that is, if it can represent a string, if $exists, it can also represent scalar single quotation marks: no reference to other variable values, $is an ordinary character, that is, as a string, do not recognize variable symbols reverse apostrophe: command replacement The output result variable after extraction command execution = reverse apostrophe equals variable = $() [root@localhost ~] # ps aux | wc-l204 [root@localhost ~] # num= `ps aux | wc-l` [root@localhost ~] # echo $num203 [root@localhost ~] # abc=$ (ps aux | wc-l) [root@localhost ~] # echo $abc203

Please enter the service you want to manage how to manage your service (option: start,status,stop)

Assign readread [- p prompt message] to variable from keyboard input [root@localhost] # vim demo.txtstatistics. Please enter an integer: "scoreecho" your score is $score "[root@localhost ~] # sh demo.txt" Please enter an integer: 996 your score is 996 ~

Input and output from the console

Operation of java

5.5 set the scope of the variable export set the globally available format 1:export variable name format 2:export variable name = variable value two formats can be mixed

Export can define a variable as a global variable, so that it can be used by both switching bash environments and switching users.

[root@localhost ~] # echo $abc203 [root@localhost ~] # bash [root@localhost ~] # echo $abc [root@localhost ~] # exitexit [root@localhost ~] # echo $abc203 [root@localhost ~] # export $abc 'only the variable name' bash: export: `203identifier: not a valid identifier [root@localhost ~] # export abc [root@localhost ~] # bash [root@localhost ~] # echo $abc203 [root@localhost ~] # exitexit [root@localhost ~] # 5 .6 Operation of integer variables exprexpr variable 1 operator variable 2 [operator variable 3]. Commonly used operator addition operation: + subtraction operation:-multiplication operation: * multiplication must be added\, because in the Shell language * on behalf of wildcard symbol division: / Modulus (remainder) operation:% [root@localhost ~] # expr 3 + 25 [root@localhost ~] # expr 9-10-1 [root@localhost ~] # expr 9 / 100 [root@localhost ~] # expr 10 / 91 [root@localhost ~] # expr 10 / 81 [root@localhost ~] # expr 6 / 32 [root@localhost ~] # expr 3\ * 26 [root@localhost ~] # expr 3 * 2expr: syntax error [root@localhost ~] # expr 39% 54 [root@localhost ~] # echo $(expr 3 + 3) 6 [root@localhost ~] # sum='expr 3 + 3''single quotes' [root@localhost ~] # echo $sumexpr 3 + 3 [root@localhost ~] # sum= `expr 3 + 3` 'backstroke' [root@localhost ~] # echo $sum66: special shell variables 6.1 environment variables are created in advance by the system Used to set the user's work environment profile: / etc/profile, ~ / .bash_prolile6.2 common environment variables PWD\, PATHUSER, SHELL, HOME [root@localhost ~] # vim / etc/profileMAIL= "/ var/spool/mail/$USER" export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL [root@localhost ~] # echo $MAIL/var/spool/mail/root [root@localhost ~] # echo $HOSTNAMElocalhost.localdomain [root@localhost ~] # echo $PATH/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin [root@localhost ~] # PATH= "$PATH:/root" [root@localhost ~] # echo $PATH/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin:/root

Add environment variables

6.3 position variable

Expressed as a number between $n and n = 1 to 9

[root@localhost ~] #. / myprog.sh 'one' two three four five' six''$1, the first position parameter''$6 The sixth position parameter'[root@localhost ~] # vim demo.shsum=0sum= `expr $1 + $2`echo "the total number of scripts executed for $sum" echo "is $0" echo "parameter is $#" echo "details is $*" cho "executed successfully $?" [root@localhost ~] # sh demo.sh 70 80 sum of scripts executed for 150 is the number of demo.sh parameters is 2 details are 7080 executed successfully 0

The statistics are $#

Besides, there's $? Whether the execution is successful, success is 0, and non-success is non-zero.

The details are $*

6.4 predefined variable $#: number of location variables on the command line $*: contents of all location variables $?: the status returned after the last command was executed. A non-zero value indicates normal execution, while a non-zero value indicates execution exception or error $0: currently executed process / program name

/ dev/null is similar to a directory with unlimited capacity, in which all unused files can be put into it. Once put in, it cannot be recovered, so use it with caution.

Similar to / dev/null is / dev/zero, which has an infinite file, both of which are used for testing

Summarize the definition, view, reference, assignment, operation environment variable, location variable, predefined variable function and use of custom variables in redirection and pipeline operation. In order to focus on viewing the operation of all aspects of the linux server, the administrator (root) wants to customize his login environment in order to automatically display monitoring information. In addition, by writing simple shell scripts Be familiar with the basic approach of Linux automation management requirements description Welcome script welcome.sh write service control script to implement start, stop, status functions #! / bin/bashusername= `whoami`lady = 20echo "= Welcome The utilization rate of the following sections of $username==== "echo" exceeds $percent% "df-Th | awk-v percent=$percent 'BEGIN {NReneway1} {if ($6 > percent) {print $7"\ t "$6}}' [root@localhost bash] # echo" / root/bash/welcome.sh "> > / root/.bashrc [root@localhost bash] # su-rootLast login: Mon Nov 25 18:44:16 GMT 2019 on pts/2==== Welcome. The utilization rate of the following sections exceeds 20%Mounted Use%/ 25%/boot 33%.

Then write the absolute path of the script to ~ / .bashrc.

#! / bin/bash#this is zuoyesystemctl stop firewall.sevricesetenforce 0read-p "Please enter the service you want to manage:" scoreread-p "how to manage your service (option: start,status,stop)" scoreasystemctl $scorea $scoreecho "systemctl $scorea $score"

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report