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

How to write shell script based on Linux

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

Share

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

This article mainly introduces how to write shell scripts on the basis of Linux, which can be used for reference by friends who need it. I hope you will learn a lot after reading this article. Next, let the editor take you to learn about it.

Overview

The concept of Shell is derived from Unix's command interpreter. Shell not only interprets commands entered by users, but also interprets and executes command-based scripting languages. The use of shell scripts can improve the efficiency of user operations and administrators in system management. Shell scripts are good at dealing with plain text data, while almost all configuration files and logs in Linux are plain text.

How to write shell script script book writing specification 1. The script is stored in a unified directory 2. Choose the interpreter and start with #! XXX, the kernel according to #! To determine which interpreter to use to interpret the content of the script 3. Edit the script using vim, configure ~ / .vimrc to facilitate personal writing habits 4. File name specification, ending with sh to end the basic elements of shell

1.#! / bin/bash required, indicate the type of shell 2.# comment. In shell, comments are written after #, and content after # does not execute 3. 0. Variable 4. Control the special symbol in the loop branch shell. Indicate the shell2.$ variable used to execute the script. Contrary to the backslash escape character, use the following ordinary character as the variable name, such as $a for the value of the variable a. When the variable character length exceeds 1, enclose 3. 0 in {}. Single quotation marks. All the generated characters are ordinary characters, that is, all the original echo'my $SHELL'4. Except for $, escape character\ and inverted quotation mark `, the contents in double quotation marks are ordinary characters. 5. The string inside the inverted quotation mark (the key next to the number 1) is executed as a shell command line interpretation (the same function can also be used with $()), and the result replaces the entire part of the inverted quotation mark. 6. A backslash is an escape character that turns a special character into an ordinary character. Using a backslash (\) before a character prevents shell from interpreting the following characters as special characters. 7. * for example, yum.* represents 0 or more special characters that can make yum. It can also be yum.a, yum.ab, yum.abc. Of course, there can be more than one letter after the decimal point. It represents any character example, yum.?. It could be yum.a yum.b yum.c. Note, however, that there must be any character 9 after the decimal point. [] represents any [abcdef] in square brackets, which can be any letter in abcdef, and of course it can be a number [-]. It represents a range of [a] z, which represents all the letters between an and z. [^] ^ is a reverse selection symbol. [^ abc] means that as long as you don't abc any of these three characters, you can assign the command replacement output to variable 11. {} you can generate the desired string through parenthesis expansion Parentheses can contain consecutive sequences or multiple items separated by commas, with consecutive sequences consisting of a starting point and an end user@computer: ~ $echo {a dir1,dir2,dir3 c} a b cuser@computer: ~ $echo user {1 dir1,dir2,dir3 8} user1 user5 user8user@computer: ~ $echo {0.. 10} 0 1 2 3 4 5 6 7 8 9 10user@computer: ~ $mkdir {dir1,dir2,dir3} user@computer: ~ $ls-ld dir {1pm 2pm 3} variable

The shell variable can hold the path name, file name, or a number, and so on. It is divided into three categories:

Local variables: (local variables) are used only in the Shell where they were created, and they can be used and modified at will within the shell program. Environment variables: can be used in the Shell that created them and any subroutines derived from them. Some variables are created by the user, while others are dedicated (such as PATH, HOME). They are part of the system environment, and you don't have to define them, you can use them in shell programs. It can also be modified in shell. Internal variables: provided by the system. Unlike environment variables, users cannot modify them. Local variable Local variable uses the variable name = value 1 in the script for the user's current shell lifetime. There can be no spaces 2 on both sides of the equal sign. The value contains spaces and must be enclosed in double quotation marks. 3.Shell variables can be used in uppercase and lowercase letters. Case-sensitive variables are weakly typed. There is no need to declare type # variable declaration and assignment format variable = value (no spaces on both sides of the equal sign) # variable reference $variable name ${variable name} method 1 is recommended when the variable name is 1 character It is recommended to use method 2 when there is more than one character: $a ${abc} # clear variable unset variable name user@computer: ~ $name=Jackuser@computer: ~ $echo ${name} user@computer: ~ $unset name # Note: there is no $# setting read-only variable before name, when you do not want to change its value, you can set it to read-only variable name = value readonly variable name environment variable

Bash presets a lot of environment variables, which can be called directly in practice. Environment variables can be used for all subroutines, including editors, scripts, and applications

Built-in environment variable

HOME: represents the user's home directory. Cd ~ go to the user's home directory or use cd to return directly to the user's home directory. SHELL: which SHELL program is currently used in this environment? If bash, the default is / bin/bashPWD: the path to the user's current working directory. It indicates where the user is currently in the Linux file system. It is automatically set by Linux HISTSIZE: this is related to the "history command", once issued instructions can be recorded by the system, and the number of records is set by this value. PATH: this is the path where the file search is performed, separated by a colon (:) between the directory and the directory. Since the file search is sequentially queried by the directory in the PATH variable, the order of the directory is also important. Environment variables can be set on the command line, but these values will be lost when the user logs out. Environment variables are all uppercase must be exported with the export command # set environment variable variable-name=valueexport variable-name (environment variable name uppercase) # display environment variable env can see all environment variables echo $environment variable name (display one variable) # clear environment variable unset environment variable name

Modify the path environment variable

Modify the PATH environment variable so that the script can be executed without adding a path and directly entering the file name. # the command line modifies the environment variables as follows: mkdir shdir & & cd shdirvi hellochmod 755 hellocd ~ export PATH=$PATH:$HOME/shdir in any directory, type hello to execute the file. In this way, if the environment variable is modified incorrectly, you can restore the default value of the system by logging in again after exit exits.

Modify environment variables in the configuration file

Note that it is best to back up the old one before modifying the environment variables: export tem=$PATHecho $tem > > pathbake needs to know which configuration files the environment variables are related to: different distributions may vary, but the naming still has generality: find /-name "* profile" find /-name "* bashrc" global configuration file / etc/profile local configuration file ~ / .bashrc internal variables

Internal variables are a special type of variables provided by Linux, which are used to make judgments in programs. The values of such variables cannot be modified in shell programs.

Some of the internal variables are: $# the number of location parameters passed to the shell program $? The completion code of the final command or the shell program executed within the shell program (return value) $0 the name of the shell program $* the single string of all parameters passed when the shell program is called, "parameter 1", "parameter 2"... Parameter $@ "Parameter 1", "Parameter 2" saved in form. Saved in the form of the parameter $n the nth parameter $$the program's PIDs! PID input and output of the previous command # read reads the values of variables from the keyboard read [options] list of variable names Common options-an ANAME reads an array of input into ANAME-n NCHARS reads N characters-p PROMPT displays a prompt-r cancels transfer -s quiet mode Characters entered will not prompt-t TIMEOUT for more than the specified time, read automatically stops # echo displaying the value of a string or variable echo [options] string common options-n does not wrap last-e enables conversion of backslash control characters-E does not handle escape characters. This is the default option #! / bin/bash# enter a sentence, read-p 'please type some words, I will print them:' wordsecho $words conditional test # testtest conditional expression if the test condition is true, the test command returns 0, otherwise it returns a non-zero numeric test statement along with the if/then and case statements Each side of the control transfer structure # [] [conditional expression] square brackets that make up shell programming requires a space where the value of the conditional expression is true and returns zero, and if it is false, it returns non-zero file status judgment statement true or false-d filename if the file filename is a directory file, it returns whether the true-f filename file exists and is a normal file, then return true-r filename if the file filename is readable Return true-s filename if the length of the file filename is greater than 0, return true-w filename if the file filename is writable, return true-x filename if the file filename is executable, return true-e filename file whether there is an absolute path to the #! / bin/bash# input file Determine whether the file exists read-p 'input file path:' fileif [- e $file] then echo 'file exists' else echo 'file does not exist' fi conditional statement if [conditional expression] then command sequence 1else command sequence 2fi when the test value of "conditional expression" is true, execute "command sequence 1", otherwise, execute "command sequence 2". The commands in the command sequence can be one or more. If [conditional expression]; then command sequence fi executes the "command sequence" when the test value of the conditional expression is true, otherwise, executes the command following the conditional statement. The semicolon between the conditional expression and then acts as a command delimiter. Syntax form 3 if test conditional expression 1 then command sequence 1elif [conditional expression 2] then command sequence 2else command sequence 3fi this is a two-layer nested conditional statement, when "conditional expression 1" is true, execute "command sequence 1", otherwise, if "conditional expression 2" is true, execute "command sequence 2", otherwise Execute Command sequence 3, which is part of the second conditional statement.

#! / bin/bash

# determine whether the input path is a file or a directory

Read-p 'please input the file path:' file

If [- d $file]

Then

Echo 'this is a directory'

Elif [- f $file]

Then

Echo 'this is a file'

Else

Echo 'wrong file type, or the file do not exist'

Fi

Operator meaning N1-eq N2 determines whether the number N1 and N2 are equal, if equal, returns 0, otherwise, returns 1n1-ne N2 to judge whether the number N1 and N2 are unequal, if not, returns 0, otherwise, returns 1n1-lt N2 to determine whether the number N1 is less than N2, if so, returns 0, otherwise, returns 1n1-gt N2 to determine whether the number N1 is greater than N2, if so, returns 0, otherwise Return 1n1-le N2 to determine whether the number N1 is less than or equal to N2, if so, return 0, otherwise return 1n1-ge N2 to determine whether the number N1 is greater than or equal to N2, if yes, return 0, otherwise, return 1 string operator meaning string if the string string is not empty, return true-n string if the string string length is greater than 0, return true-z string if the string string length is 0 Return true string1 = string2 if the strings string1 and string2 are equal, return true string1! = string2 if the strings string1 and string2 are not equal, return true logic operator meaning E1-an e2 logical expression E1 and e2 are both true, return 0, otherwise, return 0 if one of the 1e1-o e2 logical expressions E1 and e2 is true, otherwise, return 1! E1 returns 0J if the logical expression E1 is not true, otherwise, return 1 loop statement for variable name in parameter list do command list done assigns the elements in the "parameter list" to the "variable name" in turn, executes the "command list" after each assignment, and the "parameter list" represents the value range of the "variable name" ((initialize the variable value; end the loop condition) Do command sequence donewhile [conditional expression] do command list done iterates through the command list until the value of the conditional expression is false. Until [condition] do command sequence Done until the end of the loop when the condition is met #! / bin/bash# renames all files in the specified directory (parameter passing $1) with the suffix .txt to * .docdirectory=$1if [! $directory] then echo "please input the argument directory" exitfifiles= `ls ${directory} `for file in $files Do if [- f ${file}] echo $file then suffix=$ {file#*\.} echo $suffix if [[$suffix= = "txt"]] then prefix=$ {file%\. *} mv $directory/$file $directory/$prefix.doc fi fidone function functionname () {command list return} function is called as follows: functionname arguments Thank you for reading this article carefully I hope the editor will share the Linux basis of how to write shell script content to help you, but also hope you support a lot, pay attention to the industry information channel, encounter problems to find, detailed solutions waiting for you to learn!

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: 299

*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