Random Talk about shell scripts

Source: Internet
Author: User
Tags set time

I. about the shell

Shell, English is shell, the meaning of the shell, as in the computer, there is also a layer of meaning, that is, the shell can be seen as a computer system encapsulation of the shell for the user to use, so the user can manipulate the shell is to enter a series of commands to achieve various purposes, Then the shell can also be called the command interpreter .

Under the shell, a user can type a single line of commands and the shell interprets a line to make it perform different tasks in turn, which is called Interactive , and if the command is less interactive or convenient, and makes the commands transparent, the user can distinguish the causal relationship;

But if you want to execute a batch of commands, do not need to know that the process just want to know the result, or a high degree of repetition, then a row of a line of the shell line of the interpretation is very time-consuming and laborious, so you can use another way is batch processing , That is, you can write a shell script, the shell script and the programming language are similar, there are variables and process control statements, but the shell script is to interpret the line, that is, the shell will be the script in a row of a line to take out, the equivalent of a line of users to type, But compared with the interactive, it is much easier.


Two. Shell execution principle

For historical reasons, there are many types of shells, such as bash, SH, CAH, ksh, tcsh, etc., and you can view all the known (but not necessarily installed) shells in the system below the current path /etc/shells :

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/82/A2/wKiom1ddTTWwFbHJAAAF5t7vcyI835.png "title=" Bash.png "alt=" Wkiom1ddttwwfbhjaaaf5t7vcyi835.png "/>


For the current shell, such as bash, when you type a command interactively, it does not itself execute a command, because it is possible that this command is a malicious command that infringes the current process, so it creates a child process that lets the child process execute the shell command. But for shell scripts, when creating a good one shell script that runs like a command, Bash creates a sub-process to run the shell script, which is also a bash, so When it comes to executing commands in a shell script, which is equivalent to creating a child process to execute a command in a shell script, you can draw the following:


650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/82/A2/wKiom1ddUdfg1rTZAAALXsJk0iI664.png "title=" QQ picture 20160612202340.png "alt=" Wkiom1ddudfg1rtzaaalxsjk0ii664.png "/> So, when you execute multiple commands in a shell script, you need to create multiple processes to execute one by one, In spite of this, it is still much simpler than interactive;


Three. Shell scripts

    • Operating mode

In the shell script writing, ' # ' represents the comment, which is equivalent to '//' in C, but only in the first line, in the shell script, the first line must declare the command interpreter to be used, in the following form:

#!/bin/bashecho "This is a shell test"

The use of ' # ' in the first line does not represent a comment, it indicates that the script uses the following interpreter/bin/bash to interpret the execution; ' #! ' is called shebang;


chmod u+x Shell Script

First, because the shell script does not need to be compiled, but for the shell script file that was just created, it did not execute permissions at first, so you can add the permissions of the shell owner to the executable and then run the shell script:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/82/A1/wKioL1ddXHPD_g7EAAAOl4Di72I118.png "title=" chmod u +x.png "alt=" Wkiol1ddxhpd_g7eaaaol4di72i118.png "/>


Command interpreter shell Script

To run a shell script, you can still specify which command interpreter is required to interpret execution in addition to the command interpreter used in the script's writing:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/82/A1/wKioL1ddXCGDTq34AAAFl65HWos727.png "title=" Bin-bash.png "alt=" Wkiol1ddxcgdtq34aaafl65hwos727.png "/>


In addition to specifying/bin/bash, you can specify any command interpreter that is already installed on the current system, and of course, it is still possible to remove the '/bin/' to explain it using only one bash, as well as other interpreter SH:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/82/A1/wKioL1ddXcDDr5sOAAAIqaHtg0c521.png "title=" other Test.png "alt=" Wkiol1ddxcddr5soaaaiqahtg0c521.png "/>


    • Shell variables

As a rule, shell variables consist of all caps and underscores, and there are two types of shell variables:

Environment variables:

As mentioned in the process, the child process inherits the environment variables from the parent process, so the child processes that are created to execute the commands in the shell script and script inherit the shell environment variables of the parent process;

Use the PRINTENV command to display the environment variables for the current shell process:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/82/A1/wKioL1ddadTz-q9hAAB1hMstdWY448.png "title=" Printenv.png "alt=" Wkiol1ddadtz-q9haab1hmstdwy448.png "/>


Local variables:

The environment variable is the concept of all processes, and the local variable is the shell-specific concept, the local variable exists only in the current shell process, with the SET command can display all the variables defined in the current shell process (including environment variables and local variables) and functions;

Define a variable format in the shell as follows:

Valname=value

There is no space on either side of the equal sign, because if separated by a space, the valname is interpreted as a command, which is then interpreted as the parameter of the command;

A variable is determined to exist only in the current shell process, and export can be exported to an environment variable, while using unset can be deleted:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/82/AA/wKioL1deWLmhEM8fAAB3ZshJrj0917.jpg "title=" local variable. jpg "alt=" wkiol1dewlmhem8faab3zshjrj0917.jpg "/>


Unlike defining variables in a language, defining variables in the shell can be defined directly without specifying the type of the variable, such as a string, integer, or float, all of which are defined using Valname=value; in fact, in the shell, all variables are strings, For example, the definition of Val=15,val is actually a string "15" rather than an integer; in the shell, if a variable that is not defined is evaluated, an empty string:

#!/bin/bashecho "This is a shell test" val1=22//define variable VAL1 value to 22val2=11//define variable VAL2 value = 11res=0//$ (()) means that the value of the variable is taken out into an integer, only The +-*/and () operators are supported, and only integer operations Let res=$ ((Val1+val2)) echo $RES//symbol $ represents the contents of the FETCH variable echo ${VAL3}//can also use an undefined variable, except that the content is an empty string

Operation Result:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/82/B1/wKioL1demDzQqaZgAAAGnXRoMps008.png "title=" $ (()). PNG "alt=" Wkiol1demdzqqazgaaagnxromps008.png "/>


In the above program example, the contents of a variable can be $valname followed by the variable name, or ${valname}, but with curly braces is not easy to cause ambiguity, such as:

The intention is to VAL1 after the content of the Abcecho $VAL 1ABC//Will VAL1ABC as a variable echo ${VAL1}ABC//Remove the value of VAL1 and then follow the ABC


    • Anti-quotes ' and $ ()

In general, the similarities between the anti-quote ' and $ () are all available for command substitution, which means that the enclosed command is executed and then handed to the appropriate object or output:

#!/bin/bashecho ' pwd ' echo $ (PWD)

To run the script:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/82/B3/wKiom1denn7R9MM5AAAHqZJ4Vik783.png "title=" $ (PWD) . png "alt=" Wkiom1denn7r9mm5aaahqzj4vik783.png "/>

It is important to distinguish between $ () and $ (()), where the contents of the former can only be commands, which are used for arithmetic operations;


But the anti-quotes and $ () are different, as follows:

val=10 echo ' echo \ $VAL ' echo $ (echo \ $VAL)

In the C language, ' \ ' is an escape character, which is used to remove the special meaning of the subsequent character instead of the literal meaning, so the above code expects the output to be "$VAL", but the running program will find:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/82/B4/wKiom1deqEXS1wzaAAAHRkEYa1Y963.png "title=" The escape character. png "alt=" Wkiom1deqexs1wzaaaahrkeya1y963.png "/>

The output of the inverted quote is to remove the contents of the variable, and does not escape the following ' $ ' into literal value, while $ () in ' \ ' escapes ' $ ' to the literal value of the contents of the variable is not removed, output "$VAL" to achieve the expected value;


And if you change the above two lines of code to:

val=10 echo ' echo \ \ $VAL ' echo $ (echo \ $VAL)

To run the script:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/82/B2/wKioL1deqfzj7BJlAAAHSOQe3Sw793.png "title=" The escape character. png "alt=" Wkiol1deqfzj7bjlaaahsoqe3sw793.png "/>

So the results of the analysis:

Although the same command is replaced, it can be seen in the anti-quotes that ' \ \ ' is equivalent to an escape character ' \ ', while $ () is normal an escape character ' \ ' escapes the character that is followed by its literal meaning;


    • eval command

The eval command is used to make the necessary substitutions of the parameter commands followed, and then executes the command, that is, eval will scan the command line two times, replace it for the first time, and then execute the command for the second time;

For ordinary simple commands, there is no difference:

#!/bin/bash echo "This was a shell test" echo "Hello World" eval echo "Hello World"

To run the script:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/82/B2/wKioL1der53zCUUFAAAHuZ1-RWA301.png "title=" Helloworld.png "alt=" Wkiol1der53zcuufaaahuz1-rwa301.png "/>


However, for the following programs:

#!/bin/bashecho "This is a shell test" val=100str= "echo \ $VAL" Echo ${str}eval Echo ${str}

To run the program:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/82/B4/wKiom1detPDz5DC6AAAH-Fru14s480.png "title=" Eval.png "alt=" Wkiom1detpdz5dc6aaah-fru14s480.png "/>

Direct echo will output the contents of the variable directly, where the ' $ ' symbol is escaped in the contents of the STR string, indicating that the direct echo does not take out Val values;

With the eval command, however, the contents of STR are escaped first, then the command line after Eval is run, and the value of Val is extracted from the ' $ ' symbol, so the eval command can be seen as performing those one-off and not complete, It is a command that requires a further replacement before the correct conclusion is reached;


    • Single brackets [] and double brackets [[]]

Single brackets []:

1. [ for the condition test, it is not a symbol but a command, used to determine the true and false of the following conditions, and set the corresponding exit code, and in the C language of the determination of the condition is different, the use of [ to determine the condition, if true, the exit code is 0, If False then the exit code is 1;

#!/bin/bashecho "This is a shell test" read str//Compare strings, it is strongly recommended to add the same characters on both left and right sides to ensure that when the input is empty, you can still compare ["x$str" = "xred"]echo $? ["x$str" = = "Xyellow"]echo $? ["x$str" = = "Xblue"]echo $? ["x$str" = = "Xpink"]echo $?


To run the program:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/82/B3/wKioL1dewYrx9-0OAAAHpW8R0XM291.png "title=" [].png "alt=" Wkiol1dewyrx9-0oaaahpw8r0xm291.png "/>

The matching conditions were set to exit code 0, and the mismatch was 1;

For the comparison of integers, it is necessary to use-GT (greater than),-lt (less than),-eq (equals),-ge (greater than or equal),-le (less than equals) to compare;

2. [] Another purpose is to describe the matching range of a character as part of a regular expression;


double brackets [[]]:

[[]] can also be used for conditional judgment, but can be said to be [] the enhanced version, because in its internal conditional judgment statement to support the ' && ', ' | ', ' > ' and ' < ' and other C language symbols, and if in [] the internal want to make and or judgment, you need to use a (and), -O (or) to connect;

Chestnuts as follows:

#!/bin/bashecho  "This is a shell test" read score//input score if [  $score  -ge 90 -a  $score  -le 100 ];then  //score between 90 and 100 for Excellence      echo  "You are excellent" elif [  $score  -lt 90 ] & & [  $score  -ge 80 ];then //score between 80 and 89 is good      echo   "You are great" elif [[  $score  < 80 &&  $score   > 59 ]];then   //scores between 60 and 79 for passing     echo  "You are  good "else                                           //less than 60 sub-grid           echo  "sorry,you failed" fI 

To run the program:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/82/B7/wKiom1dfWLbR-RFsAAAZxy1Pbfc719.png "title=" Score.png "alt=" Wkiom1dfwlbr-rfsaaazxy1pbfc719.png "/>

It should be emphasized here that [] and [[]] are commands in the shell, so they should be separated from the arguments followed by them, otherwise they may error, and in [[]] only support ' > ' and ' < ', do not support ' >= ' and ' <= ';


    • Crond timed execution of shell scripts

Crond is a daemon in a Linux system that can be used to schedule a specified task or wait for certain tasks to be performed after startup, so When you edit a shell script and want the shell script to run regularly, you can add it to the user's crontab file and start it, so that Crond will run the script to complete the scheduled task according to the set time.


Chestnut Time:

First, write the following command in the shell script:

#!/bin/bashdatetime=$ (date)//Extract the current system time//Copy the Test.txt file under a specific directory to a backups.txt in a specific directory $ (cp/home/lounuo/test_6_12/ Test.txt/home/lounuo/test_6_12/backups.txt)//Append the current system time to the Backups.txt file echo ${datetime} >>/home/lounuo/test_ 6_12/backups.txt


Under the current user with the crontab-e command to write their own crontab, the path is /var/spool/cron, the file name is the user name:

*/1 * * * */home/lounuo/test_6_12/test.sh

means to execute a command every other minute, which is the test.sh script, which means to back up the contents of the Test.text file to the Backups.txt file every minute ;

It should be emphasized here that the path still needs to be indicated in the shell, otherwise the crond will create a backups.txt file by default in the user directory at execution time, and the Test.txt file to be copied will of course not be found, so you will only see a timestamp ;


Use the service Crond restart restart the Crond task regardless of the Crond state:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/82/B8/wKioL1dfc1qR85qYAAAGnGHtT2o112.png "title=" Crond Restart.png "alt=" Wkiol1dfc1qr85qyaaagnghtt2o112.png "/>


The content at the beginning of the backups.txt is empty; Modify the contents of test.txt every minute, and then open Backups.txt, using

tail-f backups.txt commands are observed as follows:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/82/B9/wKiom1dfdIeQDNuUAABvFEPiweY627.png "title=" Backups.png "alt=" Wkiom1dfdieqdnuuaabvfepiwey627.png "/>

Here in order to observe the convenience of the time set is relatively short, the actual use of time can be set to more appropriate backup time, so you can customize a backup mechanism, each time you change the contents of a file is automatically backed up a copy, so that the shell script into the Crond timer task, It improves the efficiency of user and Shell interaction with command and result.



Finish

This article is from the "Knock Code good Sleep zzz" blog, please be sure to keep this source http://2627lounuo.blog.51cto.com/10696599/1789051

Random Talk about shell scripts

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.