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

Shell script programming specifications and variables

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

Share

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

Main content Shell script programming specification Shell script application scene Shell programming specification pipeline and redirection Shell script variable custom variable special variable Shell script overview concept of Shell script commands to be executed are sequentially saved to a text file to give the file executable permission Can be run can be combined with a variety of Shell control statements to complete more complex operations Shell scripts application scenarios repetitive operations batch transaction processing automation operation and maintenance service running status monitoring scheduled task execution of the first Shell script 1. Write script code

Using the vim text editor, write one Linux command per line in order of execution:

[root@localhost ~] # vim first.shcd / boot/ switch directory pwd / / display the current directory Is-Ih vml* / / view all files starting with "vml" 2. Give executable permissions

There are three kinds of permissions for general files, read (r), write (w), and execute (x). Usually a Shell script is written without execute (x) permission, so we need to give it execution permission.

[root@localhost ~] # chmod + x first.sh / / just use the chmod + x command followed by the Shell script name to [root@localhost ~] # 3. Execute script file

Method 1:. / + script file path (the permission must be executed before it can be executed, and the current directory will not be changed after execution)

[root@localhost] #. / first.sh / boot-rwxr-xr-x. 1 root root 5.7m August 9 23:19 vmlinuz-0-rescue-41b16d21413d4ea6b21c13fddca8e20a-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x86_64 [root@localhost ~] #

Method 2:. + script file path (execution permissions are not required to execute)

[root@localhost] #. First.sh / boot-rwxr-xr-x. 1 root root 5.7m August 9 23:19 vmlinuz-0-rescue-41b16d21413d4ea6b21c13fddca8e20a-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x86_64 [root@localhost boot] #

Method 3: sh + script file path (execution permission is not required to execute, and the current directory will not be changed after execution)

[root@localhost] # sh first.sh / boot-rwxr-xr-x. 1 root root 5.7m August 9 23:19 vmlinuz-0-rescue-41b16d21413d4ea6b21c13fddca8e20a-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x86_64 [root@localhost ~] #

Method 4: source + script file path (execute without permission)

[root@localhost] # source first.sh / boot-rwxr-xr-x. 1 root root 5.7m August 9 23:19 vmlinuz-0-rescue-41b16d21413d4ea6b21c13fddca8e20a-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x86_64 [root@localhost boot] # 4. Perfect the composition of script

A complete Shell script requires script declarations, comments, and executable statements.

The [root@localhost ~] # vim first.sh #! / bin/bash / / script declares that it tells the system what interpreter the script needs to execute, no matter which Shell is used. # This is first script / / comment message indicating the role of the script cd / boot/echo "the current directory is located at:" / / output friendly message pwdecho ", where files starting with vml include:" ls-lh vml* "

Execute the script again after improvement, and the effect is as follows:

[root@localhost ~] #. / first.sh is currently located in: / boot, where files starting with vml include:-rwxr-xr-x. 1 root root 5.7m August 9 23:19 vmlinuz-0-rescue-41b16d21413d4ea6b21c13fddca8e20a-rwxr-xr-x. 1 root root 5.7m August 23 2017 vmlinuz-3.10.0-693.el7.x86_64 [root@localhost] # Redirection and Pipeline Operation 1. Interactive hardware equipment

Standard input: receives data entered by the user from this device

Standard output: output data to the user through this device

Standard error: an execution error message is reported through this device.

Type device file description number default device standard input / dev/stdin0 keyboard standard output / dev/stdout1 display standard error output / dev/stderr2 display 2. Redirect operation

A simple demonstration of redirected input:

[root@localhost opt] # cd / opt/ [root@localhost opt] # touch aaa.txt bbb.txt [root@localhost opt] # lsaaa.txt bbb.txt rh [root@localhost opt] # tar czvf test.tar.gz * .txt > status.txt / / create a package Save the output to the status.txt file [root@localhost opt] # lsaaa.txt bbb.txt rh status.txt test.tar.gz [root@localhost opt] # cat status.txt / / View the status.txt file aaa.txtbbb.txt [root@localhost opt] #

Standard error output demo:

[root@localhost opt] # tar jxvf test.tar.gz-C / opt/ 2 > > status.txt / / extract the previously created package in the wrong format and append the output error message to the status.txt file [root@localhost opt] # lsaaa.txt bbb.txt rh status.txt test.tar.gz [root@localhost opt] # cat status.txt / / View the status.txt file You can see the appended error message aaa.txtbbb.txtbzip2: (stdin) is not a bzip2 file.tar: Child returned status 2tar: Error is not recoverable: exiting now [root@localhost opt] #

I won't do the rest of the demonstration, it's more or less the same.

3. Pipe operation symbol "|"

Output the result of the command on the left as the processing object of the command on the right

Command format: cmd1 | cmd2 [.. I cmdn]

[root@localhost ~] # grep "bash$" / etc/passwdroot:x:0:0:root:/root:/bin/bashjiang:x:1000:1000:jiang:/home/jiang:/bin/bash [root@localhost ~] # grep "bash$" / etc/passwd | awk-F:'{print $1 root / bin/bashjiang / bin/bash [root@localhost ~] # Shell variable function, type 1. Function of variable

Providing specific parameters for flexible management of Linux systems has two meanings.

Variable name: use a fixed name, preset by the system or user defined

Variable value: can be changed according to user settings and changes in the system environment.

two。 Type of variable

Custom variables: defined, modified, and used by the user

Environment variables: maintained by the system and used to set up the work environment

Position variables: passing parameters to the script from the command line

Predefined variables: a class of variables built into Bash that cannot be modified directly.

Custom variable 1. Define a new variable

Variable names begin with an alphabet or underscore, are case-sensitive, and the first character cannot start with a number. There can be no spaces in the middle. Underscores can be used.

You can't use punctuation, you can use keywords in bash (you can use the help command to see the reserved keywords).

Format: variable name = variable value

[root@localhost] # Product=Python [root@localhost] # Version=2.7.13 [root@localhost] # 2. View the value of a variable

Format: echo $variable name

[root@localhost] # echo $Product Python [root@localhost ~] # echo $Product $VersionPython 2.7.13 [root@localhost ~] # 3. Symbol at the time of assignment

Double quotation marks: allows other variable values to be referenced by the $symbol

[root@localhost ~] # echo "$Product" java [root@localhost ~] #

Single quotation marks: reference to other variable values is prohibited, and $is regarded as a normal character

[root@localhost ~] # echo'$Product'$Product [root@localhost ~] #

Reverse apostrophe: command replacement to extract the output after the execution of the command.

[root@localhost ~] # ls-lh `which vim`-rwxr-xr-x. 1 root root 2.2m August 2 2017 / usr/bin/vim [root@localhost] # 4. Assign a value to a variable from keyboard input

Format: read [- p "prompt message"] variable name

The script reads as follows:

[root@localhost ~] # vim script.shemaking raceme Bash read-p "Please enter an integer:" numecho "the integer you entered is: $num"

The implementation results are as follows:

[root@localhost ~] # chmod + x script.sh [root@localhost ~] #. / script.sh Please enter an integer: 88 the integer you entered is: 88 [root@localhost ~] # 5. Set the scope of the variable

The export command can set a variable as a global variable, otherwise our variables in the current bash environment will be invalidated in other bash environments.

Format 1: export variable name

Format 2: export variable name = variable value

[root@localhost ~] # echo $Product / / output variable java [root@localhost ~] # bash / / change bash environment [root@localhost ~] # echo $Product / / output variable / / this variable cannot be found Because the bash environment does not have the variable [root@localhost ~] # exit / / exit Back to the previous bash environment exit [root@localhost ~] # export Product / / declare the variable Product as the global variable [root@localhost ~] # bash / / switch the bash environment [root@localhost ~] # echo $Product / / output variable java again / / output succeeded [root@localhost ~] # 6. Operation of integer variables

Format: expr variable 1 operator variable 2 [operator variable 3].

Common operators

Addition operation: + subtraction operation:-multiplication operation:\ * / / Linux system "*" is a wildcard, so add "\" symbol for translation and division operation: / module (remainder) operation:%

Simple operation demonstration:

[root@localhost opt] # expr 11 + 2233 [root@localhost opt] # expr 11-22-11 [root@localhost opt] # expr 6 / 23 [root@localhost opt] # expr 6\ * 212 [root@localhost opt] # expr 6% 42 [root@localhost opt] # Special Shell variable environment variable

Environment variables are created in advance by the system to set up the user's working environment.

Configuration file for system environment variables: / etc/profile

Configuration file for user environment variables: ~ / .bash_profile

Common environmental variables

PWD 、 PATH 、 USER 、 SHLLE 、 HOME

[root@localhost opt] # echo $PWD/opt [root@localhost opt] # echo $PATH/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin [root@localhost opt] # echo $USERroot [root@localhost opt] # echo $HOME/root [root@localhost opt] # echo $SHELL/bin/bash [root@localhost opt] # location variable

Expressed as a number between $n and n from 1 to 9.

The simple addition script is as follows:

[root@localhost opt] # vim site.shemale echo binbinBash # perform addition operation echo "value of the first position variable: $1" echo "value of the second location variable: $2" sum= `expr $1 + $2`echo "the sum is $sum"

Add with position variables:

[root@localhost opt] # chmod + x site.sh [root@localhost opt] #. / site.sh 33 45 value of the first location variable: 33 value of the second location variable: 45 summation 78 [root@localhost opt] # predefined variable $#: number of location variables on the command line $*: contents of all location variables $?: the status returned after the last command is executed. When the return status value is 0, the execution is normal. A value other than 0 indicates an exception or error in execution $0: the name of the currently executed process / program

Make changes to the addition script above as follows:

#! / bin/bash# performs addition operation echo "value of the first location variable: $1" echo "value of the second location variable: $2" sum= `expr $1 + $2`echo "summation number of $sum" echo "variables: $#" echo "all variable contents: $*" echo "name of the currently executed script: $0"

The implementation results are as follows:

The value of the first location variable: 33. The value of the second location variable: 45. The summation number is 78. The number of variables is: 2. All variable contents: 33 45. Name of the currently executed script:. / site.sh [root@localhost opt] #

After execution, use "echo $?" Command to see if the execution is normal (result is 0, execution is normal):

[root@localhost opt] # echo $? 0 [root@localhost opt] #

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