Linux Shell Script Basic Learning Details (full version) one

Source: Internet
Author: User
Tags file copy readable

Basics of Linux Shell scripting here we first talk about the shell of the basic syntax, the beginning, comments, variables and environment variables, to do a basic introduction, although not related to specific things, but lay the foundation is to learn easily after the premise.
1. Linux Scripting Basics
1.1 Syntax Basic Introduction 1.1.1 The beginning of the program must start with the following line (must be in the first line of the file): #!/bin/sh symbol #! is used to tell the system that the parameter behind it is the program used to execute the file. In this example we use/BIN/SH to execute the program. When you edit a script, you must also make it executable if you want to execute the script. To make the script executable: Compile chmod +x filename so that you can use the./filename to run 1.1.2 note in shell programming, a sentence that begins with # represents a comment until the end of the line. We sincerely recommend that you use annotations in your programs. If you use annotations, you can understand the script's function and how it works in a very short time, even if you haven't used the script for quite a long period of time. 1.1.3 Variables in other programming languages you must use variables. In shell programming, all variables are made up of strings, and you do not need to declare the variables. To assign a value to a variable, you can write:

Copy CodeThe code is as follows: #!/bin/sh #Assign a variable: a= "Hello World"
# now print the contents of variable A: echo "A is:" Echo $a

Sometimes variable names are easily confused with other words, such as:

Copy CodeThe code is as follows: num=2 echo "This is the $NUMND"

This does not print out "This is the 2nd" and simply prints "This is the" because the shell will go to search for the value of the variable numnd, but this variable has no value. You can use curly braces to tell the shell that we're printing num variables:

Copy CodeThe code is as follows: num=2 echo "This is the ${num}nd"

This will print: This is the 2nd
Variables that are processed by the Export keyword by the 1.1.4 environment variable are called environment variables. We do not discuss environment variables, because environment variables are typically used only in logon scripts.

This is explained here, and below we will be exposed to the substantive parts of the specific Linux Shell Script Foundation.
Learn more about Linux Shell Scripting Basics (ii)
Linux Shell Scripting Basics Course here is the second lesson, detailing shell commands and process Control, and this section introduces three types of commands that you should compare when learning.

The Linux Shell Scripting Fundamentals Course is all about syntax basics, annotations, variables, and environment variables, and here's the first part of the shell command and control process, where you can use three types of commands in a shell script, and the control flow is next.

1.1.5 shell command and Process Control

There are three types of commands that can be used in shell scripts:

1) Unix command:

Although you can use any Unix command in a shell script, there are some relatively common commands. These commands are usually used for file and text operations.

Common command syntax and functions

echo "Some text": Print text content on the screen

LS: File list

Wc–l filewc-w filewc-c File: Count the number of words in the file count the number of characters in the file

CP sourcefile destfile: File copy

MV oldname newname: Renaming files or moving files

RM file: Deleting files

grep ' pattern ' file: Search for strings within a file such as: grep ' searchstring ' file.txt

Cut-b colnum File: Specifies the range of files to display and outputs them to a standard output device such as: Output from 5th to 9th characters per line cut-b5-9 file.txt never be confused with cat commands, this is two completely different commands

Cat file.txt: Output file contents to standard output device (screen)

File somefile: Get the files type

Read Var: Prompts the user for input and assigns the input to the variable

Sort file.txt: Sorting rows in a file.txt file

Uniq: Delete columns that appear in a text file such as: sort File.txt | Uniq

Expr: Perform mathematical operations Example:add 2 and 3expr 2 "+" 3

Find: Search for files like: Search for Find by file name. -name Filename-print

Tee: Output data to standard output devices (screens) and files such as: Somecommand | Tee outfile

basename file: Returns a file name that does not contain a path such as: Basename/bin/tux will return Tux

DirName file: Returns the path of the files such as: Dirname/bin/tux will return/bin

Head file: Print text file at the beginning of a few lines

Tail File: Print text file at the end of a few lines

Sed:sed is a basic find-and-replace program. You can read text from standard input, such as a command pipeline, and

The result is output to standard output (screen). the command is searched 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 are used to extract fields from a text file. By default, the field separator is a space, and you can use-f to specify additional delimiters.

Cat File.txt | Awk-f, ' {print $ ', ' $ i} ' here we use, as field separators, while printing the first and third fields. If the contents of the file are as follows: Adam Bor, Indiakerry Miller, the USA command output is: Adam Bor, Indiakerry Miller, USA

2) Concepts: piping, redirection 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 for a row containing "Hello" in File.txt 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 multiple commands.

Redirect: Outputs the result of the command to a file instead of the standard output (screen).

> Write files and overwrite old files

>> add to the end of the file, preserving the contents of the old file.

Anti-Short Slash

Use a backslash to make the output of one command a command-line argument for another command.


Find. -mtime-1-type F-print

Used to find files that have been modified in the last 24 hours (-mtime–2 represents the last 48 hours). If you want to hit a package with all the files you find, you can use the following script:


# The Ticks is Backticks (') not normal quotes ('):

TAR-ZCVF lastmod.tar.gz ' Find. -mtime-1-type F-print '

The second point is here, the following is the Linux shell Script Basic Learning we will continue to talk about the control process.
Learn more about Linux Shell Scripting Basics (iii)
The first two words of the Linux shell scripting are finished, but the control process is not yet in the time to speak, this will control the three parts of the process if, case, select.
Basic learning of Linux shell scripts the third, in front of the shell command and process Control, because the space does not speak of process control, today's flow control we are only introduced in the previous three parts of the If case and select. There are three parts behind that are covered only in the Linux shell Scripting basics.

1.1.5 shell command and Process Control (2)

3) Process Control


The "If" expression executes the following part if the condition is true:

If ....; Then


Elif ...; Then





In most cases, you can use test commands to test the condition. For example, you can compare strings, determine whether the file exists and whether it is readable, etc...

The condition test is usually represented by "[]". Note that the space here is important. The space to ensure the square brackets.

[-F "somefile"]: Determine if it is 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:


If ["$SHELL" = "/bin/bash"]; Then

echo "Your login shell is the bash (Bourne again shell)"


echo "Your login shell isn't bash but $SHELL"


The variable $shell contains the name of the login shell, which we compared with/bin/bash.

Shortcut operator

A friend familiar with C might 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 above example prints "This computer uses Shadow Passwors" if the/etc/shadow file exists. Same OR operation (| |) is also available in Shell programming. Here's an example:



[-R "$mailfolder"] "{echo" Can not read $mailfolder "; exit 1;}

echo "$mailfolder have mail from:"

grep "^from" $mailfolder

The script first determines whether the mailfolder is readable. Prints the "from" line in the file if it is readable. If unreadable or the operation takes effect, the script exits after the error message is printed. Here's the problem: we have to have two commands.

-Print error message

-Exit Program

We use curly braces to put two commands together as a command in the form of an anonymous function. The general functions are mentioned below.

Without the and and or operators, we can do anything with an if expression, but using and or operators is much more convenient.

Case: The expression can be used to match a given string instead of a number.

Case ... in

...) do something here;;


Let's look at an example. The file command can identify the type of files for a given file, such as:

File lf.gz

This will return:

Lf.gz:gzip compressed data, deflated, original filename,

Last Modified:mon 23:09:18 2001, Os:unix

We use this to write a script called Smartzip, which automatically extracts compressed files of bzip2, gzip, and zip types:


Ftype= ' file ' $ "'

Case ' $ftype ' in

"$1:zip Archive" *)

Unzip "$";;

"$1:gzip Compressed" *)

Gunzip "$";;

"$1:bzip2 Compressed" *)

Bunzip2 "$";;

*) echo "File" can not is uncompressed with smartzip ";


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:


$ $ is the string

3. Selsect

The select expression is an extended application of bash and is particularly adept at interactive use. Users can choose from a different set of values.

Select Var in ...; Do



.... Now $var can be used ....

Here is an example:


echo "What's your favourite OS?"

Select Var in "Linux", "Gnu Hurd" "Free BSD" and "other"; Do



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

Above is the content of this talk, control process is more, here first introduce these three.

Learn more about Linux Shell Scripting Basics (iv)
Linux Shell Scripting Basics We'll go on to learn the control flow in the Linux shell script, which focuses on the loop and quotation marks of the control flow.
In a Linux shell script Basic Learning We talked about the Linux shell script control process of If, select, case, here is the Linux shell script control process loop and quotation marks, control process this part of the content is more, There is also a part of the content about here document.


Loop expression:

While ...; Do



While-loop will run until the expression test is true. Would run while the expression, the We test for is true.

The keyword "break" is used to jump out of a loop. The keyword "Continue" is used to skip to the next loop without executing the rest of the section.

The For-loop expression looks at a list of strings (strings separated by spaces) and assigns them to a variable:

for Var in ...; Do



In the following example, the ABC is printed separately to the screen:


For Var in A B C; Do

Echo "Var is $var"


The following is a more useful script showrpm, which functions to print some RPM package statistics:


# List A content summary of a number of RPM packages

# usage:showrpm Rpmfile1 rpmfile2 ...

# example:showrpm/cdrom/redhat/rpms/*.rpm

For Rpmpackage in $*; Do

If [-R "$rpmpackage"];then

echo "=============== $rpmpackage =============="

Rpm-qi-p $rpmpackage


echo "Error:cannot Read file $rpmpackage"



There is a second special variable, $*, that contains all the input command-line parameter values.

If you run showrpm openssh.rpm w3m.rpm webgrep.rpm

At this point $* contains 3 strings, namely openssh.rpm, w3m.rpm and webgrep.rpm.

5. Quotation marks

The program expands wildcard characters and variables before passing any parameters to the program. The so-called extension means that the program replaces the wildcard character (such as *) with the appropriate file name, and the variable is replaced with the variable value. To prevent the program from making this substitution, you can use quotation marks: Let's take a look at an example, assuming there are some files in the current directory, two JPG files, mail.jpg and tux.jpg.

1.2 Compiling shell scripts

#ch #!/bin/sh mod +x filename

Cho *.jpg∪ slow Teman tip Wine together Ltd U Chung Yuen oldest? /filename to execute your script.

This will print out the results of "mail.jpg tux.jpg".

quotation marks (single and double quotation marks) prevent this wildcard extension:


echo "*.jpg"

Echo ' *.jpg '

This will print "*.jpg" two times.

Single quotes are more restrictive. It prevents any variable expansion. Double quotes prevent wildcard expansion but allow variable expansion.



echo "$SHELL"

Echo ' $SHELL '

The result of the operation is:




Finally, there is a way to prevent this extension by using the escape character-the backslash:

Echo *.jpg


This will output:



Linux Shell Scripting Basics Here, the control process has a little bit of here document content to analyze next time.

Linux Shell Script Basic Learning Details (full version) one

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.