Creation and execution of Linux shell scripts

Source: Internet
Author: User
Tags file copy

 

Scripting is essential when you are doing Linux testing. Using Linux recently, I felt tired of hitting the keyboard too often, so I thought of the shell script. You can write too many commands into a script so that you can eliminate the time you hit the keyboard every time you execute a shell file. So I searched the internet for some of the contents of the script programming under Linux.

The shell is not just a collection of commands, but also a great programming language. You can automate a large number of tasks by using the shell, which is particularly well-suited to system administration tasks, especially those that are more important for ease of use, maintainability, and portability than efficiency.

Users can edit shell script files, such as VI, Gedit, and so on, using any text editor.

The name of the shell script can be arbitrarily defined, and do not have any suffix names, such as can write abc,smartzip such names.

Let's start by writing a shell script:

1. The program must start with the following line (must be placed in the first line of the file):
#!/bin/sh
The 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.

2. Notes
In shell programming, a sentence that begins with # represents a comment until the end of the line. As with other programming languages, we should add as many comments as possible when scripting, so we can understand the script's function and how it works in a very short time, even if we don't use it for quite a long time.

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: variable name = value
You can add a dollar sign ($) in front of the variable to remove the variable value:
#!/bin/sh
#对变量赋值:
A= "Hello World"
# now print the contents of variable a:
echo "A is:"
Echo $a

4. 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:
Calculates the number of words in a file by the number of lines in a file calculates the number of characters in a 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:
Specify the range of file content to display and output them to a standard output device such as: Output from 5th to 9th characters per line cut-b5-9 file.txt never confuse 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 output the results to a 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
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: Adambor, Indiakerry Miller, $, USA command output: Adambor, 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.
Command: Find. -mtime-1-type F-print is 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:

#!/bin/sh
# The Ticks is Backticks (') not normal quotes ('):
TAR-ZCVF lastmod.tar.gz ' Find. -mtime-1-type F
-print '

3) Process Control
The "If" expression executes the following part if the condition is true:
If ....; Then
....
Elif ...; Then
....
Else
....
Fi
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

5. Execute the Script
The sh file under Linux has execute permission by default. We can use the command: ls-l file_name to see the user's permissions on the file. If you do not have Execute permissions, you can add the following command: chmod +x file_name. You can then run the script by running the command: SH xx.sh. Of course different systems may not be exactly the same and need to be based on the actual situation. For example, some Linux is./xx.sh can be run.

In summary, the shell's call to a shell script can take 3 different ways:

(1) One is to use the file name as a parameter to the shell command, which is called in the format:

$ Bash Script_file

This invocation is only used when the script file to be executed does not have executable permissions.

(2) Another method of invocation is to change the access permission of the script file to executable so that the file can be called as an execution file.

The specific method is: $chmod +x script_file

$PATH = $PATH: $PWD

$script _file

(3) When executing a script file, the shell generates a shell (that is, a subprocess) to execute the commands in the file. Therefore, the variable value of the script file cannot be passed to the current shell (that is, the parent process). In order for the variable values in the script file to be passed to the current shell, you must precede the command file name with ".". That

$./script_file

“.” The function of the command is to execute the command in the script file in the current shell, rather than producing a child shell to execute the command in the command file.

Go from: http://moko39848381.blog.163.com/blog/static/13982733120102271644576/

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.