Linux Shell Scripting Basics Here we first talk about the shell's grammatical basis, beginning, annotation, variables and environment variables, to do a basic introduction, although not involved in specific things, but lay a good foundation for later learning easy premise.
1. Linux Scripting Basics
Basic Introduction to 1.1 grammar
1.1.1 Start
The program must start with the following line (must be on the first line of the file):
#!/bin/sh
The symbolic #! is used to tell the system that the parameters behind it are the programs used to execute the file. In this example we use/BIN/SH to execute the program.
When you edit a good script, you must also make it executable if you want to execute the script.
To make the script executable:
Compile chmod +x filename so you can use./filename to run
1.1.2 Notes
In shell programming, comments are expressed in sentences that begin with # until the end of the line. We sincerely recommend that you use annotations in your programs.
If you use annotations, you can understand how the script works and work in a very short period of time, even if you haven't used it for a very long time.
1.1.3 Variable
You must use variables in other programming languages. In shell programming, all variables are composed of strings, and you do not need to declare variables. To assign a value to a variable, you can write this:
Copy Code code as follows:
#!/bin/sh
#对变量赋值:
A= "Hello World"
# now print the contents of variable a:
echo "A is:"
Echo $a
Sometimes variable names can easily be confused with other words, such as:
Copy Code code as follows:
num=2
echo "This is the $NUMND"
This does not print out "This is the 2nd" and only prints "This is the" because the shell searches for the value of the variable numnd, but the variable has no value. You can use curly braces to tell the shell what we want to print is the NUM variable:
Copy Code code as follows:
num=2
echo "This is the ${num}nd"
This will print: This is the 2nd
1.1.4 Environment Variables
Variables processed by the EXPORT keyword are called environment variables. We do not discuss environment variables because, in general, environment variables are used only in logon scripts.
Here's what this is about, and we'll touch on the real part of the specific Linux shell scripting basics.
Learn more about Linux Shell Scripting Basics (II.)
Linux Shell Scripting Basics Here is the second lesson, detailing shell commands and process control, which introduces three types of commands, which we should learn more about.
Linux Shell Scripting Basics The first introduction to the grammar basics is the beginning, annotation, variables, and environment variables, which will introduce the second part of the shell command and control process, where three types of commands can be used in the shell script, and the control process is next.
1.1.5 shell command and Process Control
There are three types of commands that can be used in a shell script:
1 Unix Command:
Although arbitrary UNIX commands can be used in shell scripts, there are some relatively more commonly used commands. These commands are usually used for file and text operations.
Common command syntax and functions
echo "Some text": Print text content on screen
LS: File list
Wc–l filewc-w filewc-c file: Calculate the number of words in a file count the number of characters in a file
CP sourcefile destfile: File copy
MV Oldname newname: Renaming a file or moving a file
RM file: Deleting files
grep ' pattern ' file: Search for strings within a file for example: grep ' searchstring ' file.txt
Cut-b colnum File: Specifies the range of files to display and outputs them to standard output devices such as: Output the 5th to 9th characters per line cut-b5-9 file.txt do not confuse with cat commands, this is two completely different command
Cat file.txt: Output file contents to standard output device (screen)
File somefile: Getting files Type
Read Var: Prompts the user for input and assigns the input to the variable
Sort file.txt: Sort the rows in a file.txt file
Uniq: Delete the rows that appear in a text file for example: sort file.txt | Uniq
Expr: Mathematical operations Example:add 2 and 3expr 2 "+" 3
Find: Search for files such as: Search for Find by filename. -name Filename-print
Tee: Output data to standard output devices (screens) and files such as: Somecommand | Tee outfile
basename file: Returns a filename that does not contain a path such as: Basename/bin/tux will return Tux
DirName file: Returns the path where the files are located for example: Dirname/bin/tux will return/bin
Head file: Print the first few lines of a text file
Tail File: Print a few lines at the end of a text file
Sed:sed is a basic search and replace program. You can read text from standard input, such as a command pipe, and
Results output to standard output (screen). The command searches using a regular expression (see Reference). Do not confuse with wildcard characters in the shell. For example: Replace Linuxfocus with Linuxfocus:cat text.file | Sed ' s/linuxfocus/linuxfocus/' > Newtext.fileawk:awk is used to extract fields from a text file. By default, the field separator is a space, and you can specify additional delimiters using-F.
Cat File.txt | Awk-f, ' {print $ ', ' $} ' here we use, as a field separator, to print both the first and third fields. If the contents of the file are as follows: Adam Bor, Indiakerry Miller, USA command output is: Adam Bor, Indiakerry Miller, USA
2 Concept: Pipelines, redirects and Backtick
These are not system commands, but they are really important.
Pipe (|) The output of one command as input to another command.
grep "Hello" file.txt | Wc-l
Searches the file.txt for a row containing "Hello" and calculates its number of rows.
Here the output of the grep command is used as input to the WC command. Of course you can use more than one command.
Redirect: Outputs the results of a command to a file instead of the standard output (screen).
> Write files and overwrite old files
>> add to the end of the file and keep the old file contents.
Anti-Short Slash
Using a backslash, you can use the output of one command as a command line argument for another command.
Command:
Find. -mtime-1-type F-print
Used to find files that have been modified in the last 24 hours (-mtime–2 for the last 48 hours). If you want to make a package of all the files you find, you can use the following script:
#!/bin/sh
# The Ticks are Backticks (') not normal quotes ('):
TAR-ZCVF lastmod.tar.gz ' Find. -mtime-1-type F-print '
The second is here, the next one on Linux shell Scripting Basics We will continue to talk about the control process.
Learn more about Linux Shell Scripting Basics (III.)
The first two stories of Linux shell scripting are over, but we haven't had time to talk about the control process, which will control three parts of the process if, case, select.
Linux Shell Scripting Basics Third, we introduced the shell command and process Control, because the space is not able to speak process control, today's process control we are here to introduce the previous three parts of the If case and select. There are three more sections that can only be covered in the third lecture on the basics of Linux shell scripting.
1.1.5 shell command and Flow control (2)
3) Process Control
1.if
An "if" expression executes the part following then if the condition is true:
If ...; Then
....
Elif ...; Then
....
Else
....
Fi
In most cases, you can use test commands to test conditions. For example, you can compare strings, determine whether a file exists and whether it is readable, and so on ...
You typically use [] to represent a conditional test. Note that the spaces here are important. To ensure that the square brackets are blank.
[f "Somefile"]: To determine whether a file
[-X "/bin/ls"]: Determine if/bin/ls exists and has executable permissions
[-N ' $var]: Determine if the $var variable has a value
["$a" = "$b"]: Determine if $a and $b are equal
Execute man test to see the types that all test expressions can compare and judge.
Execute the following script directly:
#!/bin/sh
If ["$SHELL" = "/bin/bash"]; Then
echo "Your login shell is the bash (Bourne again shell)"
Else
echo "Your login shell is not bash but $SHELL"
Fi
The variable $shell contains the name of the login shell, which we compared with/bin/bash.
Shortcut operators
A friend who is familiar with C may like the following expression:
[f "/etc/shadow"] && echo "This computer uses Shadow Passwors"
Here && is a shortcut operator that executes the statement on the right if the expression on the left is true.
You can also think of it as an operation in a logical operation. The example above indicates that "This computer uses Shadow Passwors" is printed if the/etc/shadow file exists. Same OR operation (| |) is also available in Shell programming. Here's an example:
#!/bin/sh
Mailfolder=/var/spool/mail/james
[-R ' $mailfolder] ' {echo ' Can not read $mailfolder '; exit 1;}
echo "$mailfolder has mail from:"
grep "^from" $mailfolder
The script first determines whether the mailfolder is readable. If readable, prints the "from" line in the file. If unreadable or the operation takes effect, the script exits after printing the error message. Here's the problem, which is that we have to have two orders:
-Print error messages
-Exit Program
We use curly braces to put two commands together as a command in the form of anonymous functions. The general functions are mentioned below.
Without the and OR operator, we can do anything with an if expression, but it is much more convenient to use the and or operators.
2.case
Case: An expression can be used to match a given string, not a number.
Case ... in
...) do something here;;
Esac
Let's look at an example. The file command can identify a given file type, such as:
File lf.gz
This will return:
Lf.gz:gzip compressed data, deflated, original filename,
Last Modified:mon Aug 23:09:18 2001, Os:unix
We use this to write a script called Smartzip, which automatically extracts bzip2, gzip, and zip-type compressed files:
#!/bin/sh
Ftype= ' file '
Case "$ftype" in
"$1:zip Archive" *)
Unzip "$";;
"$1:gzip Compressed" *)
Gunzip "$";;
"$1:bzip2 Compressed" *)
Bunzip2 "$";;
*) echo "File of Can not is uncompressed with smartzip";;
Esac
You may notice that we are using a special variable here. The variable contains the first parameter value passed to the program.
In other words, when we run:
Smartzip Articles.zip
$ is a string articles.zip
3. Selsect
A select expression is an extended application of bash and is especially good at interactive use. Users can choose from a different set of values.
Select Var in ...; Todo
Break
Done
.... Now $var can be used ....
Here is an example:
#!/bin/sh
echo "What is your favourite OS?"
Select Var in "Linux" "Gnu Hurd", "Free BSD", "other"; Todo
Break
Done
echo "You have selected $var"
The following is the result of the script running:
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux
The above is the content of this talk, the control process is more, here first introduced these three.
Learn more about Linux Shell Scripting Basics (Iv.)
Linux Shell Scripting Basics We go on to learn the content of the control process in the Linux shell script, which mainly introduces the loop and quotation marks of the control process.
In the previous Linux shell scripting Basics, we talked about if, select, and case of the control process in the Linux shell script, and then we introduced the loop and quotation marks of the Linux shell script control process, and the control process was more There is also a section on the document.
4.loop
Loop expression:
While ...; Todo
....
Done
While-loop will run until the expression test is true. Would run while the expression so we test is true.
The keyword "break" is used to jump out of the loop. The keyword "Continue" is used to skip to the next loop without performing the remaining parts.
The For-loop expression looks at a list of strings (strings separated by spaces) and assigns them to a variable:
for Var in ...; Todo
....
Done
In the following example, ABC is printed separately on the screen:
#!/bin/sh
For Var in A B C; Todo
Echo "Var is $var"
Done
Here is a more useful script showrpm that prints some of the RPM packet statistics:
#!/bin/sh
# List A content summary of a number of RPM packages
# usage:showrpm Rpmfile1 rpmfile2 ...
# example:showrpm/cdrom/redhat/rpms/*.rpm
For Rpmpackage in $*; Todo
If [-R "$rpmpackage"];then
echo "=============== $rpmpackage =============="
Rpm-qi-p $rpmpackage
Else
echo "Error:cannot Read file $rpmpackage"
Fi
Done
Here comes the second special variable $*, which contains all the input command-line parameter values.
If you run showrpm openssh.rpm w3m.rpm webgrep.rpm
At this point the $* contains 3 strings, namely openssh.rpm, w3m.rpm and webgrep.rpm.
5. Quotes
The program expands wildcard characters and variables before passing any arguments to the program. What this means by extension is that the program replaces the wildcard character (such as *) with the appropriate filename, which is replaced with the variable value. To prevent the program from making this substitution, you can use quotes: Let's look at an example, assuming there are some files in the current directory, two JPG files, mail.jpg and tux.jpg.
1.2 Compiling the shell script
#ch #!/bin/sh mod +x filename
Cho *.jpg∪ slow Teman tip Christie U Chung Yuen oldest? /filename to execute your script.
This will print out the results of the "Mail.jpg tux.jpg".
quotation marks (single and double quotes) prevent this wildcard extension:
#!/bin/sh
echo "*.jpg"
Echo ' *.jpg '
This will print "*.jpg" two times.
Single quotes are more restrictive. It can prevent any variable from being extended. Double quotes can prevent wildcard extensions but allow variable extensions.
#!/bin/sh
Echo $SHELL
echo "$SHELL"
Echo ' $SHELL '
The results of the operation are:
/bin/bash
/bin/bash
$SHELL
Finally, there is a way to prevent this extension by using the escape character--the backslash:
Echo *.jpg
Echo $SHELL
This will output:
*.jpg
$SHELL
Linux Shell Scripting Basics Here it is, and the control process has a little bit of here document content to analyze again next time.
Current 1/2 page
12 Next read the full text