Shell scripting Learning and summarizing _linux shell

Source: Internet
Author: User
Tags case statement chmod comparison table dba lowercase readable syslog file permissions scripts are small-case
2.Unix special characters are: (; $ & * () [] ' "+ Use it to escape ()
3.Shell comments begin with #
4. Definition of function
Function Fuction_name () {
Command to execute
Use Function_name directly when calling.
5. Control structure
1) If...then statement
If [Test_command]
2) If...then...else statement
If [Test_command]
3) If...then...elif...then ... (ELSE) statement
If [Test_command]
Elif [Test_command]
4) for ... In statement
For loop_varible in Argument_list
5) While statement
While Test_command_is_true
6) until statement
Until Test_command_is_true
7) Case statement
Case $variable in


*) #option for other values

6.break, continue, exit, and return statements
Break jumps out of the whole loop body, and then executes the loop outside the next code;
Continue end this cycle, continue the next cycle;
Exit exits the entire script, usually followed by an integer (such as Exit 0), sent to the system as the return code;
Returns are used to return data in a function, or to return a result to the calling function Document
Used to redirect input to an interactive shell script or program without requiring user intervention.
Program_name << lable
Note that there is no blank between the lable tags in the program input line, and the input must be the exact data expected by the program, or it may fail.
8. Symbolic command
() run the command enclosed in parentheses in a child shell
(()) Evaluate and assign variables in a shell and perform mathematical operations
$ (()) evaluation of an enclosed expression
[] Same as Test command
[[]] used for string comparisons
$ () command substitution
' Command to replace
9. Command line arguments
Command line argument $0,$1,$2,..., $ is the positional parameter, and the $ $ is the command itself.
Command shift is used to move the position parameter to the left, as the shift command commands $ $. Shift joins a number to move multiple positions, such as Shift 3, which makes $ $. Shift is a good way to process each positional parameter in order of the parameters listed.
10. Special parameters
$* specifies all command-line arguments, as is the $@ meaning. The two only have different meanings when adding double quotes, such as
"$*" gets the entire argument list as a parameter, and "$@" gets the entire argument list and separates it into different parameters.
$? Check the return code. A successful execution of the command return code is 0, unsuccessful is a non-0 value.
11. Double quotes, single quotes and ' (Keys below ESC)
Single quotes ' to make a full reference to the content, that is, to use the text body for the variable command statement, without any substitutions, and double quotes to make a partial reference, allowing character substitution or command substitution.
' (the key below ESC) is used to execute a command or script and replace its output, which is a command substitution, with the same function having $ (). In addition, if you want to reread the value of a variable each time you use it, such as ' $PWD ', it will re-read its new value each time you use the variable.
12. File permissions and sticky bits (suid,sgid)
File permissions are read, write, execute three kinds of permissions. The file operation mode is set to always be performed as a specific user (suid), or always as a specific group member (SGID) called set sticky bit. You can use the command chmod to modify file permissions.
13. Running commands on a remote host
Ssh User@hostname Command_to_execute
such as: SSH jack@ "uptime"
14. Set Traps
When a program is forced to abort, there is an exit signal called a trap. This allows us to execute commands when the exit signal is captured, such as when the exit signal is 1,2,3,15:
Trap ' echo ' nexitting on a trapped singal '; Exit ' 1 2 3 15
Note that you cannot capture the exit signal for kill-9.
15. View user Information
Who provides user name, TTY, logon time and user login (IP) for each logged-on user
W extends to WHO, including job process time, total user process time, etc., but no user login information.
Last displays the list of users who started logging in from the Wtmp file, including logon hours, exit times, TTY, and so on. command
Displays information about the current system process.
17. Communication with users
18. Case-and-write text
Use the TR or typeset command.
Echo $VALUES | TR ' [A-z] ' [A-z] ' #将大写转换成小写; tr ' [A-z] ' [A-z] ', lowercase is converted to uppercase
Use before values
Typeset-l VALUES #将大写转换成小写; Typeset-u is converted to uppercase in lowercase.
19. Timed Run script cron
Crontab-e enters a user cron table to add a timed script, such as
On January 15, Sunday 0:12 Execute script/usr/bin/
#分 (0-59) (0-23) days (1-31) months (1-12) weeks (0-6for sunday-saturday)
0 1 0/usr/bin/
A timed task can also act at command.
20. Output control
Run silently without outputting any content to the screen: 2>&1 >/dev/null
Output to System-specified console: >/dev/console
21. Parse Command line arguments getopts
Getopts optionstring VARIABLE
Optionstring is a required variety of parameters, separated by a colon, which can be omitted if no arguments are required. If there is a colon before optionstring, then any mismatch will load a varible in the
The function of using getopts is to parse out parameters and then act on this parameter to do different things. Such as:
While Getopts:s:m:h:d:p: TM
Case $TM in
Do something

Do something

Exit 1

22. Document-By-line processing
While Read line
Echo "$LINE"
23. function Select Command Create Menu
Select menu in Yes No Quit
Case $menu in
Do something

Do something


Do something


Shell Script Learning

1, set up the operating environment

Writing at the top of a script: #!/bin/bash2,shell variable and Assignment Str=hello
In Linux, variables need not be defined and are assigned directly when they are used. For example: STR, note that there can be no space on either side of the equal sign str= ' ls-l/tmp/sh ' If you want to assign the execution result of a command to a variable, the = number to the right should be enclosed
echo "$str"
View the value of a variable, where the result is: Hello3, which assigns the specified variable read name from the keyboard input character or value, such as: Enter Lishi from the keyboard, the value of name is: Lishi4, "", ",", "double quote, single quotation mark, inverted quotation mark difference
echo "My name is $name"
Displays the string, but contains the value of the escape character referencing its variable. Results in Example: My name is Tom
Echo ' My name is $name '
Displays the contents of the single quotation marks as they are, as a result: the My name is $name
Echo ' Ls-l '
Executes the characters in inverted quotes as commands and displays the results of the execution. 5, plus, minus, well-behaved, in addition to the calculation of modulo. Note that you enclose it in inverted quotes.
Expr ' 5 + 4 '
Expr ' 5-4 '
Expr ' 5 \* 4 '
Expr ' 5/4 '
Expr ' 5% 4 '
If you are operating within a script, the inverted quotation marks include all the contents of the = number to the right. such as: sum=0sum= ' expr $sum + 1 ' 6, command for text manipulation

Less can flip up and down.
More can screen one screen of the turn
Head look at the first 10 lines of text argument-n 5 to show only the first 5 rows
Tail look at the end of the text 10 lines, plus-f parameters, can look at the changes in real-time log files. See the Tomcat log file changes. Tail-f/usr/tomcat/logs/canitsl.out

Parameter-N 5 indicates that only the first 5 lines are displayed 7,$? indicates that the last command was executed correctly, 0 is normal, and 1 indicates an error
Ls/tmp/hello, if the/tmp/does not have hello for this file or directory. $1 instead of 08,./test Lishi Wangwu
$ program name, the name of the first parameter, in the case of $ test
A string of $* parameters, in cases where $* is Lishiwangwu
$ #传递给程序参数的总数目, in the case of $ #为29, the variables in Linux are divided into global environment variables and user Configuration variables
The Working environment directory that the Global environment variable sets for all users in the system, in/etc/profile
The user Configuration variable is for a user. In the directory where users log in,. bash_profile 10, redirect redirection is to change the direction of the original input output, the default is the screen output device, the keyboard is an input device. ">" is an output redirection character. "<" is an input redirect character. ">" only holds the correct information, "2>" stored the wrong information, each deposit before the contents of the file before the empty and put into such as: ls/usr >/tmp/aaa the/usr directory of all file and folder name information in the expiration/tmp/aaa file.
such as: Ls/test 2>/tmp/aaa If there is no/test folder, then there will be errors, then 2> will put the error message into the AAA file.
">" can create new files, such as: >
">" Can empty a file, such as files have content, I > then, content empty ">>" double greater than the number together becomes an append function, after the contents of the previous file appended. For example: cat/tmp/sh >>/tmp/aaa appends all file and directory information in the/TMP/SH directory to the AAA file. The contents of the pre-AAA file will not be erased. Cat >, you can enter a lot of content on the screen, press Ctrl+d will exit. And then Cat,
Just enter the content, all in the file 11, input redirect such as: Cat > A.txt <<eee, from the screen input to a.txt, until the input EEE to end!!!! Such a combination is often used to automate the logging of certain logs, or to write information.

Sysprofile=/etc/profilecat >> $SYSPROFILE <<eof
Export java_opts= "-xms64m-xmx768m"
Export path= $JAVA _home/bin: $JAVA _home/jre/bin:: $PATH
Export classpath=.: $JAVA _home/lib: $JAVA _home/lib/dt.jar: $JAVA _home/lib/tools.jar
EOF12, Pipeline: The output of the previous command as input to the next command. As the name implies is the role of two pipelines before and after the connection.
Connect the end of the previous pipe to the head of the next pipe. Ls-l/tmp/test | Wc-l statistics the number of files and directories in the/tmp/test directory. The files and directories in the/tmp/test directory are displayed in columns. The displayed results are used as the source of information for the WC-L command. 13, conditional Judgment statement string comparison: =,!=,-n: To determine whether the string length is greater than 0, greater than 0 is true,-Z: To determine whether the string length is equal to 0, equals 0 is True
Number comparison:-eq equal,-ge greater than equal,-le less than equal,-ne not equal,-gt greater than,-lt less than
Logical judgment:! Non-,&& with, | | Or
File judgment:-D directory Judgment,-F file judgment,-R readable, W-writable,-x executable test Condition 1 comparison conditions 2 such as: Test 1-eq 1
[Condition 1 comparison condition 2] such as: [1-eq 1],[-n ""]
[' Who | wc-l '-le]&& echo ' yes ' to determine if the current system's number of logged-in users is less than or equal to 10, yes, output YES

16, circular statement:

The while condition is true, execution
Done Example: j=1
while ((j<=10)) or while [J-le 10]
echo "J= $j"
j= ' expr $j + 1
Done If statement:
Else this can also be elif and fi nesting
fi Example: x=4;y=7if [$x-eq $y]
echo "Equality"
echo "Not Equal"
FI case variable in
Value 1) statement;;
Value 2) statement;;
*) statement;; #如果数值不在范围之中, execute this line of example: User=whoamicase $USER in
echo "You are Lishi";
echo "Welcome";;
echo "You are ROOT"
echo "Hi root";;
echo "you are admin";
echo "Admin,hello";; * echo "Current user is not lishi,root,admin";;
Esac For loop Example: Displays each file information in the/tmp/sh directory with A For loop. The value of the variable i is each file in the/tmp/sh directory, such as for I in "a" "B" "C", at which time the variable I takes the value of each loop to a,b,cpath=/tmp/sh/
For i in ' LS $path '
Ls-l $i
Example: #用for与if相结合的手法, showing an even number between 1 and keyboard inputs
#注意if语句的双括号read x
For ((i=1;i<= $x; i++))
If [$i% 2 = 0]
echo "$i"
DONE14, Function # defines an additive function sum, then enters two digits from the keyboard, and then calls the SUM function
# Note that the function must be placed before the call to the function sum ()
A= $x
b= $y
Total= ' expr $a + $b '
echo "total = $total"
}echo "Please enter two number:"
Read X
Read Y
Sum $x, $y
Shell start:

Shell has Bsh,bash,cash, etc.

1, in Linux when the administrator user logged in, the prompt is: #, the general user login in when the prompt is: $
Login to enter, exit or to switch users, with: Exit command, normal exit.
2, view the shell version in the current system and view it in the/etc/shell directory.
3, view the default shell version of different users in the system,/etc/passwd view the current user's Shell,echo shell
4, directly with the command to change a user's shell environment: CHSH system username, according to the prompts to enter a new shell path, such as:/bin/bash
5, view the current user's environment variable and ID number, set | grep User,set | grep uid or, viewing/etc/passwd files
6, see where a command is located which command such as: which ifconfig when some of the general user's command prompt cannot be found
or execution, it is generally not the path of the command that is added to the environment variable. Setting environment variables with the Export command
7, view previously used commands history history-c to purge previously used commands
8, in the shell to distinguish the end of a command. Multiple commands can be in a row
9, debug the shell script with the. script file name or bash script filename
10, file permissions are divided into three categories:
A, the file owner: the user who created the file
b, same group of users: Any user in the user group that owns the file
C, other User: That is, a user who does not belong to the user group that owns the file
such as:-rwxr-xr-x 1 root root 217 08-10 19:51
The first character represents the type of file, whether it is a folder or a normal file example-a normal file
The following 9 characters are divided into three paragraphs, the first paragraph is the file owner's permissions
The second paragraph is the permissions of the same group of users, and the third is the permissions of other users
Assign permission: G is to represent the same group of users, O is on behalf of other users
chmod go+wx./ permission to write and execute to the same group of users and other users
chmod u+wr./ give himself read and write permission
chmod o+wrx./ the right to read, write, and execute other users
Go to the right and the right to assign the same, just replace "+" with "-" on it
chmod GO-RW./B.C the right to read and write to the same group of users and other users

11, general permissions can also be expressed in numbers: 4: Read, 2: Write, 1: Execute,
If you assign permissions to a file with a number, write 3 digits, such as: 764, to indicate
The user is a read-write execution, the same group of users are read-write, other users are reading permissions.
12, when assigning permissions to files and folders, they do not interfere with each other unless you assign permissions to a folder with the-R parameter
Then, all the content under the folder gives you the same permissions as the folder, and use the-R carefully.
13, when viewing folder permissions, use: Ll-d/tmp/sh-d is to view the folder, otherwise it will only
Lists the contents of the folder.

14, change the file to the user, Chown oracle/tmp/sh/
Change the group to which the file belongs, chown:oracle/tmp/sh/
At the same time, to change the files of the users and groups, Chown oracle:dba/tmp/sh/ so of the user and group information is:
-rwxrwxr-x 1 Oracle DBA 264 07-28 15:57/tmp/sh/
15,id command to see which user is currently, and which group is fairly informative
16,groups See how many groups the system currently has, groups user name such as: Groups Oracle, viewing user-owned groups
17,getent Group name: Getent Group DBA See which users are in the DBA group
18, create a user and add it to the specified group Useradd wangcai-g root

19, when a script needs to be executed by a user of the owner or group, it needs to be suid,guid
When a file has a suid or GUID set, if the file does not have permission to execute, then it is not meant to set the Suid or GUID, with an uppercase "S"
Said. 4 represents suid,2 on behalf of the GUID
such as: example, first use Chown to change the file to the user, and then use chmod change file Suid and GUID permissions
-rwxr-xr-x 1 root root 632 08-15 17:31
Chown Oracle
-rwxr-xr-x 1 Oracle Root 632 08-15 17:31
chmod 6751
-rwsr-s--x 1 Oracle Root 632 08-15 17:31

20, execute a script with the specified user su-oracle-c "/tmp/sh/"
Execute this script as Oracle
21, create Shortcut ln-s/tmp/sh 1 Create Shortcut 1 point to/tmp/sh, Access 1 is equivalent to accessing/tmp/sh.
22, Scheduled tasks:
Use service Crond status to view the Cron service state, or service Crond start if it is not started.
Basic usage:
List the current crontab tasks
Delete the current crontab task
CRONTAB-E (solaris5.8 above is crontab-r)
Edit a crontab task, Ctrl_d end
crontab filename
The format of the crontab is: the time-sharing and Lunar Week command (separated by a space in the middle).
The entries for the crontab file are read from the left, the first column is divided, and so on, and the last column is the command that needs to be executed.
Each column is called a crontab domain in which you can use-to connect a time range, such as Monday through Friday, which can be expressed in 1-5.
A single point of time can be separated by a number, such as Monday and Thursday, which can be expressed as 1, 4. If there is no special limit to the field that represents the time, it can be represented by a * number. Each time entry contains 5 fields, separated by a space.
For example, I would like to run the file in the bin directory every night 21:30, so the command should be:
* * * */APP/BIN/CLEANUP.SH (Note: the date, month, and week fields are indicated by *) because no qualifying date, month, or week is required.
For example, I want to run files for 1, 10, 20 00:00 a month, so the command should be:
1,10,20 * */APP/BIN/BACKUP.SH (Note: The month and week fields are indicated by the * number because there is no need to qualify months and weeks)
0 */2 * * * Date
Crontab-e then edits the contents in the open file, such as: 0 */2 * * Date, save exit.
You can also put the contents of the 0 */2 * * * date into a filename file, and then use the crontab filename
Add the content to the crontab and then use Crontab-l to see the contents of the filename file.
Make the configuration file effective: If you have the configuration file in effect, you will have to restart Cron, remember that since the Cron profile is modified under each user.
Also reboot the cron server,/etc/init.d/crond restart. Edit the/etc/crontab file with one line at the end: 5 * * * Root init 6 This configures the system to automatically restart at 5-point 30 per morning.
You need to set up the Crond service that starts automatically after the system starts, and can be added at the end of the/etc/rc.d/rc.local
Service Crond Start
If you also need to load additional services at the system start ten, you can continue to add the start command for other services.
For example: Service mysqld start

A summary of shell script learning

1. Character truncation:

If the character truncation is a generic path, you can use both the basename and dirname tools:
BaseName can truncate a filename from a file path
For example:
$ basename/home/file.tar
DirName can be truncated to a directory path from a file path
For example:
$ dirname/home/file.tar
Do not use external tools for character truncation
Bash has its own features to truncate variables, generally using "# #", "#", "%", "%", "*" group
together to achieve. For example:

Copy Code code as follows:

$ string=hellowbashshell
$ echo ${string##*sh}
$ echo ${string#*sh}
$ echo ${string%%sh*}

-----------------------Page 2-----------------------
$ echo ${string%sh*}
"#" is dropped from the beginning of the character and immediately after the match
"# #" means to remove from the beginning of the character, searching for the longest match of the entire string to remove
"%" is removed from the end of the character and immediately removed when the match is made into a public
Percent% means that the end of the character is removed and the longest match is searched for the entire character to remove
The "*" wildcard character, commonly associated with "# #" or "#", is placed on the left side of the search string, for example: ${string#*sh} (on the left of SH
, and "%" or "%" are placed on the right side of the matching string, for example: ${string%%sh*}
Common skills:
Take filename in path: ${path##*/} (same function as basename)
Directory path in Path: ${path%/*} (same function as dirname)
Fetch file extension: ${path##*.}
2. The receipt of the independent variable
Receives arguments passed in from the command line, the first parameter is represented by $, and the second argument is $ ... Analogy
Note: $ represents the script filename. Another common use in shell programming is "$@", which represents all the parameters
Number. You can use a loop to traverse this argument. If you use Java analogy, you can think of $@ as man.
The array defined in the function
3.if statement:
if [condition]
Note: Spaces are required between "if" and "[", and if you do not have spaces, the shell will report syntax errors
Mistaken. That's what I've been wasting for so long.
-----------------------Page 3-----------------------
Conditon Test Type comparison table
Operator Description Example
File comparison Operators
-e filename true if filename exists [-e/var/log/syslog]
-D filename True if filename is a directory [-d/tmp/mydir]
-f filename If filename is a regular file, [-f/usr/bin/grep]
is True
-l filename If filename is a symbolic link, then [-l/usr/bin/grep]
is True
-R filename True if filename is readable [-r/var/log/syslog]
-W filename true if filename is writable [-w/var/mytmp.txt]
-X filename is true if filename is executable [-l/usr/bin/grep]
Filename1-nt if filename1 than filename2 [/tmp/install/etc/services-nt
Filename2 new, then true/etc/services]
Filename1-ot if filename1 than filename2 [/boot/bzimage-ot
Filename2 old, it is true arch/i386/boot/bzimage]
String comparison operators (note the use of quotes, which is a good way to prevent spaces from disrupting code)
-Z String True if string length is zero [-Z ' $myvar]
-N String true [-n ' $myvar] if string length is Non-zero
string1= string2 If string1 is the same as string2, ["$myvar" = "One Two Three"]
is True
string1!= string2 If string1 differs from string2, ["$myvar"!= "one Two three"]
is True
Arithmetic comparison operators
Num1-eq num2 equals [3-eq $mynum]
Num1-ne num2 Not equal to [3-ne $mynum]
Num1-lt num2 less than [3-lt $mynum]
Num1-le num2 less than or equal to [3-le $mynum]
NUM1-GT num2 is greater than [3-GT $mynum]
Num1-ge num2 greater than or equal to [3-ge $mynum]
Feel like the IF in bash is more intelligent than some other languages, in bash, test the existence and comparison of a file
The size of two numbers is no different;)
-----------------------Page 4-----------------------
4.for statement
The statements in bash are always so human, very close to the natural language, in the for statement can almost
Iterate any data type similar to the collection (maybe that's not true, but I really don't think it's better
words to replace).
Look at an example:
For args in $@
Echo $args
Save the code entry as set to executable (chmod +x
$./ arg1 arg2 Arg3 arg4
In this example, we use the "$@", which represents all command-line arguments. Here for
Traversing it, the system iterates through the command line parameters from the $@ and puts him in the args, finally using
echo $args for output.
For more often use is traversal directory, the following example is used to list all the files and text in the current directory
The name of the piece folder
Copy Code code as follows:

$ for file in *
> Do
> Echo $file
> Done

Here the * represents the current directory, listing the names of all the files and folders, where the folder
and file you are not to be separated, if you need, you should use if [D-${file}] to make a judgment.
-----------------------Page 5-----------------------
What's even more interesting about file traversal is that you can connect multiple expressions after "in". Other words
You can traverse multiple directories at once.
The following code copies the files from the Go folder and do folders in the current directory to the FO folder
Copy Code code as follows:

For args in./go/*./do/*
CP ${args}./FO
echo "Copying ${args} to./fo/${args}"

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