1. Background
The Linux shell is a basic skill, often replaced by scripts such as Python, because of the weird syntax combined with poor readability. Since it is the basic skills, it is necessary to master, after all, the process of learning shell script, still can learn a lot of Linux system content. Linux scripting Masters are not accessible to everyone, but it is necessary to implement some common basic functions with some simple shells.
2. The subject
1) Warm Up
The following example shows how to pass parameters to the script, how the script gets the parameters, the If-else judgment, the use of variables, and so on.
#!/bin/bashif [[$#-lt 1]]; Then echo "args count must > 1" echo "Uage:bash +x example01.sh [args ...]" exitfiarg=$1if [[$arg-GT 10]]; Then echo "$arg >" Else echo "$arg <" fi
This script is called in the following way:
Bash +x example01.sh 5
2). Array, function pass parameter, loop
The following example shows the basic use of arrays, functions, loops, and so on.
#!/bin/bashif [[$#-lt 1]]; Thenecho "args count must > 1" echo "Uage:bash +x example01.sh [args ...]" Exitfi[email protected]for arg in $args; Doecho $argdonefunction Fun () {echo $1}fun "Hello Shell" fun2 () {echo "Linux"}fun2
Note that in the function fun, you get the function arguments, not the arguments that are passed in when the script is called. [Email protected] is the list of arguments passed in when the script call is obtained.
3). Use of the while loop and several other loops, case, and expression expr
#!/bin/bashif [[$#-lt 1]]; Then echo "args count must > 1" echo "Uage:bash +x example01.sh [args ...]" Exitficase " Install") echo "Operation type is install" ;; " Uninstall ") echo" Operation type is uninstall " ;; *) echo "Operation type isn't support" ;; Esacfor ((i=0;i<3;i++)) do if ((i==1)) then continue fi echo $idonefor i in ' seq 5 ' do echo "Loop $i" done
Note that the case * is not all, but the input value is not in the case, equivalent to default. Keywords such as continue/break can be used in loops, very similar to those in other languages such as Java.
4). Script references to each other
Through source or. can refer to a function or variable in another script
first.sh
function Fun () {echo ' I am from first.} File=first
second.sh
. First.shfunecho $file
With bash +x second.sh execution, you can call the fun function and use the file variable in second.sh.
Both. and source can implement variables in a reference to the first file.Note: If a variable with the same variable name of multiple scripts is referenced at the same time, subsequent values will overwrite the previous variable without error.
5). About Error Handling
A) is there a variable $ in the shell? , this variable records the result of the last script execution, or 0 if the normal end, otherwise it is a value of 0;
b) If the Set-o Errexit is implemented in the shell script to exit when the error is encountered, it can avoid generating more errors;
c) If an error occurs during shell execution, it can be redirected to output to a file, such as Command >> filename2>&1
6). Dictionary
The dictionary in the shell is a very good data structure that can be easily handled by the configuration
#!/bin/bashset-o Errexithput () {eval "hkey_$1" = "$ $"}hget () {eval echo ' ${' "hkey_$1" '} '}hput k1 v1hget k1declare-a dicdic = ([key1]= "value1" [key2]= "value2" [key3]= "Value3") echo ${dic["Key1"]}# output all Keyecho ${!dic[*]} #outpull All Valueecho ${dic[*]}# Access Allfor key in $ (echo ${!dic[*]}) does echo "$key: ${dic[$key]}" done
After execution, the output is as follows:
V1value1key3 Key2 key1value3 value2 value1key3:value3key2:value2key1:value1
7). Text Processing
The SED command is able to manipulate the text.
For example, there is a file sedfile, the content is as follows:
12345
Execute "sed ' 1,3d ' sedfile, then output 4, 52 lines, that is, to do the removal of the line, notethe two lines were not deleted in the file.。
In addition to deleting, you can also do a substitution operation.
[Email protected]:~/codelab# sed ' s/1/0/g ' sedfile 02345[email protected]:~/codelab# cat Sedfile 12345
We found that at the time of the output, 1 was replaced with 0;
There is also a very powerful tool for text processing-awk
Let's first look at the basic processing of awk-to get the desired text by dividing it by a comma (,);
Here we can see that awk can split the text in any form and then output it;
8). Special variables and values
The following variables usually have a fixed meaning
$# represents the number of variables, often used to loop [email protected] all parameters of the current command line. In double quotation marks, the individual arguments $* all parameters of the current command line. Placed in double quotation marks, represents the command line all parameters at the beginning of a single argument $-(hyphen) in the reference number given to the shell option $? Represents the status of the last command exit $$ indicates that the current process number, the current program name, is $! The process number that represents the most recent background command $home the current user root $ifs represents the internal field delimiter $lang the current locale default name $path environment variable $ppid parent process number $ PWD Current Working directory
The following special values can help troubleshoot problems
0 Successful exit >0 exit failed 1-125 command exit failed, the related value returned by the program is defined by the procedure (for example, exit 2 is executed within the program, return to 2) 126 command found, but cannot execute 127 Command could not find the >128 command was killed by a signal
9. Scheduled Tasks
There are scheduled tasks under Windows, and there are scheduled tasks on the Linux system as well. The crontab can be realized by using the system's own;
The output of executing cat/etc/crontab on my system is as follows:
[Email protected]:~/codelab# cat/etc/crontab #/etc/crontab:system-wide crontab# Unlike any other crontab you don ' t have To run the ' crontab ' # command to install the new version when you edit this file# and files in/etc/cron.d. These files also has username fields,# that none of the other crontabs does. shell=/bin/shpath=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin# m H Dom Mon Dow usercommand17 * * * Root CD/&& run-parts--report/etc/cron.hourly25 6* * *roottest-x/usr/sbin/anacron | | (CD/&& run-parts--report/etc/cron.daily) 6* * 7roottest-x/usr/sbin/anacron | | (CD/&& run-parts--report/etc/cron.weekly) * *roottest-x/usr/sbin/anacron | | (CD/&& run-parts--report/etc/cron.monthly) #
From here we can see how cron is used, where Cron uses the shell, and here's how the command is set up.
Minute: Represents minutes, which can be any integer from 0 to 59. Hour: Represents the hour, which can be any integer from 0 to 23. Day: Represents a date, which can be any integer from 1 to 31. Month: Represents the month, which can be any integer from 1 to 12. Week: Represents the day of the week, which can be any integer from 0 to 7, where 0 or 7 represents Sunday. Command: The commands to execute can be either system commands or script files that you write yourself.
We can use some of the following basic commands;
Usage:crontab [-u user] filecrontab [-u user] [-i] {-e |-l |-r} (default operation is replace, per 1003.2)-E (Edit u Ser ' s crontab)-L (list user ' s crontab)-R (delete user's crontab)-I (Prompt before deleting user's crontab)
10). Tips
A) Determine if the parameter is a number.
#!/bin/sh#1. $ $ is the first parameter of the script, which is passed to the awk command as the first parameter of the awk command. #2. Since there is no input file as the input stream, this is done only in the Begin block. #3. In awk, the ARGV array represents an array of arguments for the awk command, Argv[0] represents the command itself, Argv[1] represents the first argument. #4. Match is the built-in function of awk, the return value is the starting position of the matching regular expression in the string (Argv[1]), and no return 0 is found. #5. The notation of regular expressions has ensured that the matching string must be a positive integer in decimal, such as a floating-point number or a negative number, and only need to modify the regular. #6. When Awk executes, it returns the result to the ISDIGIT variable as its initialization value. #7. Isdigit= ' echo $ | awk ' {if (Match ($, "^[0-9]+$")! = 0) print "true"; else print "false"} ' #8. The above notation can also be implemented, but because there are multiple processes involved, the efficiency is lower than the following notation. isdigit= ' awk ' BEGIN {if (Match (argv[1], "^[0-9]+$")! = 0) print "true"; else print "false"} ' if [[$isdigit = = ' true ' ]]; Then echo "This is numeric variable." Number=$1Fi
b) Assign values to variables based on the system to ensure portability
#1. Use the uname command to get the current system name, and then, depending on the OS name, give the ping variable the full name of a different ping command. Osname= ' Uname-s ' #2. You can add more operating system names in the conditions of the case. Case $osname in "Linux") ping=/usr/sbin/ping;; " FreeBSD ") ping=/sbin/ping;; " SunOS ") ping=/usr/sbin/ping;; *) ;; Esac
3. Summary
These are just the basic parts of shell development, the shell is actually a very efficient, powerful language, continuous learning and accumulation will become more and more skilled.
Linux Shell Usage Notes