--book author Shenmon reprint please specify the source
Content Introduction
- Objective
- What is a shell?
- Our first shell script
- Run the shell script
- Summarize
- Part V Third lesson preview: variable in hand, shell not worry
1. Preface
The previous lesson is a Linux Discovery Tour | Part V The first lesson: Vim is a pool of things, Bao Jianfeng from sharpening out.
Now, we have learned a powerful text editor like Vim. Trust me, Vim will be very useful for our later courses.
In this lesson we can go into the center of gravity of the fifth part: Shell programming.
What is a shell?
First, the shell is the English "shell, shell" meaning. You can think of it as a "miniature programming language" embedded in an operating system such as Linux.
So the name of the "cool Shell" in the title of this lesson is inspired by the IT community Daniel Chenhao's blog "Cool Shell": http://coolshell.cn/.
The shell is not as complete as the C language, C++,java and other programming languages, but the shell language can help us do a lot of automation tasks, such as saving data, monitoring the load of the system, and so on.
We can of course write a C-language program to accomplish the tasks mentioned above. But the advantage of the Shell compared to the C language is that it is completely embedded in Linux: No installation, no compilation, and we don't need to learn too much new stuff.
In fact, the commands we've used in Linux so far, we can use them in the Shell language. For example:
lscdgrep
Wait a minute.
Since we're going to talk a lot about the shell in the fifth part, what is the shell anyway?
We will first answer this question and then write our first Shell script. In the next few lessons, we'll go into Shell programming.
Script is the extension of the batch file, is a plain text saving program, generally speaking, the computer script program is determined by a series of control computer operations operation of the combination, in which a certain logical branch can be implemented.
2. What is a shell?
From the very beginning of this series of courses, we took a look at two different environments in Linux:
Most of the time, we use a graphical interface because it is more intuitive. Different graphical interface environment is always so easy to identify, such as menu items are not the same, the icon is not the same, the color difference, and so on.
However, in the terminal command-line environment, we can implement many complex tasks that cannot be done in the graphical interface environment.
As we said in our previous course, Linux has many graphical interface environments: UNITY,KDE,GNOME,XFCE and so on, but the terminal command-line environment "looks like" the same, only one.
In fact, this is not an accurate statement. The terminal command line environment also has many kinds, corresponding is different Shell.
The difference between the different terminal command lines is not as obvious as the graphical interface, because the terminal command line is generally white on the black background. However, depending on the shell, the command line can offer different functions.
So, can we call different terminal command-line environments different shells?
That is true.
Here are a few of the main shells:
Sh:bourne the Shell's abbreviation. It can be said that the ancestors of all the shells at present.
Bash:bourne Again shell abbreviation, you can see more than Bourne shell a again,again in English is "again, again, in addition" meaning, so the description bash is an advanced version of SH, better than sh. Bash is currently the default Shell for most Linux distributions and Apple's Mac OS X operating system.
Ksh:korn the Shell's abbreviation. Generally in the Unix version of the charges are more common, but there is also a free version.
CSH:C the Shell's abbreviation. The syntax of this Shell is somewhat similar to the C language.
Tcsh:tenex C Shell's abbreviation. Optimized version of CSH.
Zsh:z the Shell's abbreviation. Compare a recent Shell, set Bash,ksh and tcsh. I used bash before the company and now it's zsh (there's a zsh configuration on Github called Oh-my-zsh, which is worth owning).
Of course, there are a lot of other shells, but we've listed some of the main ones.
What do we need to know about these various shells?
First, SH (Bourne shell) is the ancestor of all these shells. This is the oldest Shell, and is installed on almost all Unix-originated operating systems. Compared to its descendants, the "Old man" seems a little "skill is insufficient."
Bash (Bourne Again shell) is a well-known shell, the default shell for most Linux distributions, and the default shell for Apple's MAC OS X operating system. It is likely that the Shell you are currently using in your Linux is bash.
We can use it to show the evolutionary relationships of each Shell:
Now that bash is already the default Shell for most Linux distributions, what's the use of "antique" sh?
In fact, SH is always more widely used than bash. In the first lesson of this course, we introduced that Linux is a bit of a Unix-like creation. Almost all Unix-based operating systems (Linux also counted) have sh, but not every one has bash. For example, the Unix-based charging operating system, such as AIX and Solaris, uses other shells.
What can the Shell do?
The shell is the program that manages the command line. So the shell is actually waiting for you to enter those commands. Such as:
You can see that a cursor has been flashing and you can enter the command.
The Shell can also help you do a lot of things, such as:
Remember the previous command you entered in the terminal: Use the UP arrow on your keyboard to fall back to the command you executed earlier.
Search for executed commands in the history of the terminal with the CTRL + R key combination:
Ctrl + R commands in fast input history
, we can see that when we press ctrl+r this key combination, we are prompted to enter the command, and if some of the characters we entered in the beginning of the command are consistent with the commands that have been run in the history, then the command will be complete. For example, here we enter find. -name ".", the shell uses find that has been running in history. -name "."-exec grep "kdiscstatuscalleenotexist" This command to complement the whole. So we don't have to re-enter a lot of very long commands.
- Use the Tab key to automatically fill in the commands we want to enter:
TAB key Auto-complete command
, we enter GI and then press the Tab key, and the Shell prompts us for the available candidates. You can also use the Tab key to automatically complete the path of the file.
Control process (put the process into the background, pause the process (with previous lessons Linux Discovery Tour | The third part of lesson four: running in the background and merging multiple terminals we have learned Ctrl + Z can do), and so on).
REDIRECT command (used to <,>,| , and so forth symbols. Lessons before us Linux Discovery Tour | The third part of the second lesson: flow, Pipeline, redirection, three-pronged secondary school.
Define aliases: For example, you can define a very long string of commands as a short alias name (alias). For example, LL can be defined as an alias of Ls-al.
In short, the Shell provides all the basic functionality that allows you to run commands.
Remember the previous lesson on Linux Discovery Tours | Part Two: Nano text editor and terminal configuration, have we ever modified a. bashrc file?
this. BASHRC is actually bash's configuration file for this Shell. Each Linux user can customize its own. BASHRC to configure Bash. It can specify Bash's command prompt style, define aliases, and so on.
In the future, we often encounter some files in the Linux system that end with RC, such as. bashrc,.zshrc,.init.rc, and so on. Then people can't help but ask: What is the RC here mean AH?
"RC" was taken from the "runcom", developed by MIT in 1965 by the CTSS system. The relevant literature has documented this passage: "Has the function of taking out a series of commands from the file," called "Run Commands" (run is the meaning of "running" in English, command is the meaning of English "commands", so run commands is the meaning of "Run command"), Also known as "runcom", and this file is also known as a runcom (a runcom).
The general end of the RC is a configuration file, which contains the software before the run will read and run those initialization commands.
The previous lesson when we mentioned Vim, its configuration file is called. VIMRC, which is similar.
Install a new shell
At this time, your Linux system probably only installs the two shells of SH and bash, which are pre-installed programs when you install Ubuntu.
If you want to install another Shell, such as Ksh, you can install this:
sudo apt-get install ksh
Once you've installed Ksh, you'll also need to switch your current Shell (typically bash) to Ksh to take effect.
In order to switch the shell, the following command is required:
chsh
CHSH is the abbreviation for change shell, which means "switch shell" in English.
Run the CHSH command
The CHSH command prompts you to enter the program path of the shell you want to switch to after the colon. You can enter/bin/ksh (if you want to switch to Ksh), or/bin/sh (if you want to switch to SH) or/bin/bash (if you want to switch to bash), and so on. You can see that my current Shell in Ubuntu is zsh (/bin/zsh).
Why is switching the shell important for us to write shell scripts?
Because your shell script needs to rely on one shell. In short, you're using different shells (sh,bash,zsh,ksh, and so on), but the syntax is not the same.
For example, we can write the sh script. We can guarantee that the SH script will basically run on most systems, but SH's syntax is not so "pro-people".
So, what kind of shell will we use to write our shell script?
In this course, we learn about the Shell of bash because:
In most Linux systems and Apple's MAC OS X system, Bash is the default Shell.
Bash scripts are easier to write than Sh.
Bash is more common than Ksh and zsh. Although these two are more advanced than bash.
3. Our first shell script
Introducing so many shell-related knowledge points, let's write a shell script program. This script will be simple, but enough to give us a sense of the basics of creating scripts and running scripts. This is a foundation for our later course.
Creating a script file
We use Vim, the text editor we learned in the last lesson, to create a Shell script file:
vim test.sh
If the test.sh file does not exist, it will be created.
Here, we give this Shell script file a suffix of. Sh. This has become a conventional naming convention (SH is the shell's abbreviation), in fact, shell script files and ordinary text files are no different. We add. sh to emphasize that this is a Shell script file. We can give this file the name test (without the. sh suffix).
But in this course, we still follow the practice of naming it test.sh.
Specifies the shell to be used by the script
Press Enter and the above command is executed. Vim was opened, and under our noses was an empty file.
The first thing to do when writing a shell script is to specify which shell to use to "parse/run" it. The syntax of the Shell is different because of sh,ksh,bash and so on.
Since we're going to use bash in our course, we'll write on the first line of the Shell script
#!/bin/bash
In the above code,/bin/bash is the way the Bash program stores the most Linux systems, and the first #! is called Sha-bang, or shebang.
In Computer science, Shebang (also known as Hashbang) is a string line consisting of a pound sign and an exclamation mark #! , which appears in the first two characters of a text document in line one.
In the case of shebang in the document, the process loader of the Unix-like operating system parses the contents of the Shebang, interprets the content as an interpreter directive, invokes the instruction, and takes the document path containing the shebang as the parameter of the interpreter.
This line (#!/bin/bash) is not really necessary, but it guarantees that the script will be executed by the Shell we specify.
If you do not write this line, then this script file will be executed by the user's current Shell. This can be problematic: If your script is written in bash syntax and the Shell of the user running the script is Ksh, then the script should not work properly.
So remember that when you write a Shell script file, you first write the first line in the beginning of the shebang.
Run command
After the first line that starts with Shebang, we can formally encode it.
The principle is simple: just write the command you want to execute. Temporarily and before we at the command line prompt character write command is not bad.
For example:
LS: Used to list the files in the directory.
CD: Used to switch directories.
mkdir: Used to create a directory.
grep: Used to find a string.
Sort: Used to sort strings.
Wait a minute.
In short, the commands you learned in previous lessons are now available.
Well, let's start with a very simple order.
We enter the LS command. Yes, the purpose of this script file is to list the files in the directory for the time being.
#!/bin/bashls
That's all, it's simple, right?
Comments
As with other programs, we can also add comments to the Shell script file. Comments are rows that will not be executed, but can be used to explain what our script did.
The comments for the Shell script begin with # (pound sign). For example:
#!/bin/bash# 列出目录的文件ls
4. Run the shell script
We just wrote a very simple shell script file, just a few lines of code. So next, we just need to run it.
First, we save the file just now and exit Vim.
Hope you remember how to do, forget the words please go to review Linux Discovery Tour | Part V The first lesson: Vim is a pool of things, Bao Jianfeng from sharpening out.
Yes, just use the ESC key to enter interactive mode from insert mode, and then press the colon key to enter command mode, enter Wq or X, and return.
:wq
Or
:x
We re-retrieved our command prompt.
Add executable permissions to a script file
If we run the ls-l command in the current directory:
ls -l
You can see the script file that you just created:
You can see that the permissions for this file are
-rw-rw-r--
If you remember us on a Linux Discovery Tour | Part Two: Users and permissions, the right to learn about the self-willed knowledge of the authority, then you should know that the file it does not have executable permissions (because there is no x).
Therefore, we add executable permissions to it:
chmod +x test.sh
Then use the Ls-l command to see that you have the executable permission:
Run the script
We enter the following command to run this script file:
./test.sh
After the carriage return, the script file is run by bash installed in our system and the results are as follows:
Test.sh Running Results
What does this script do?
It's just a basic Linux command that executes LS. Because this script file is located in my home directory (/home/exe), it lists all the files in my home directory (and does not contain all because of many).
It seems that this script is really chicken. Why don't we just run the LS command directly at the command line, and make a lot of trouble writing a Shell script?
Trust me, the Shell script is definitely useful because it can automate a lot of commands at once, without needing you to enter them one at a time. For the time being, there is nothing in our script, and after that you will see the power of the Shell.
We can add a few more commands to this Shell script in the test.sh just now, so that it can do more things. For example, we add the PWD command to print out the path to the current directory.
#!/bin/bashpwdls
Save the file and run it again to see the results:
This time first the PWD command was called to print out the path to the current directory (/home/exe) before the LS command was run to print out the files in the current directory.
Run in debug mode
As we get deeper into shell programming, you may write long shell scripts that are more likely to have bugs in your code.
Bug is English word, the original meaning is bug, flaw, damage, commit to poverty, bug, worm and so on. Now people will be in the computer system or program, hidden some of the uncovered defects or problems referred to as a bug (vulnerability).
Therefore, we need to learn how to debug a scripting program. Use the following:
bash -x test.sh
We call bash the Shell program directly, and give it a parameter-X (which means run in debug mode), followed by the script file to debug the run.
As a result, the Shell prints out the details of the runtime of our script files, which can help us troubleshoot the problem in the event of an error.
Debug mode run Create your own commands
For now, our Shell script file needs to run like this:
./test.sh
And we need to be in the right directory.
So some other programs (commands are actually programs), such as Git,pwd,ls, and so on, why can it be executed directly from whatever directory (no need to add./such a path)?
The secret is that the directory in which these programs are stored is in the environment variable of PATH.
Path is English "path, road, route, distance, way" means. PATH is a system variable for Linux. This variable contains the path to all the programs in your system that can be executed directly.
If we enter in the terminal
echo $PATH
So we can see the "special" directories in our system.
For example in my case:
Each path is separated by a colon (:).
As you can see, there are a number of paths in my path that are duplicated and estimated to be related to my zsh from bash. Some paths have been added repeatedly.
But it's okay, the path duplication doesn't matter too much. Then I'll delete the duplicate again well.
So, as long as you copy the test.sh file to any directory in the above path list (for example,/usr/local/bin,/usr/bin, etc.), you can run your Shell script in whatever directory you want.
test.sh
Try it!
5. Summary
Originally we thought the terminal command line has only one form, actually has quite a few types of terminal: This corresponds to the different shell (shell program). The shell can manage the command prompt, as well as a variety of features, such as the history of the command (found with ctrl+r), the automatic completion of the command, and so on.
In Ubuntu, the default shell is bash, but you can also install other shells, such as ksh,zsh, and so on.
We can use the shell to automate a series of commands. You first need to create a file that contains a list of commands to run, called a shell script. This is also called Shell programming.
Depending on the kind of shell used, we have different tools to handle shell scripts. We use bash to demonstrate in this lesson, so we need to write it at the beginning of the Shell script file: #!/bin/bash
In the Shell script file, it is generally just a matter of writing the command we want to execute one line to the file.
To run a shell script (that is, run the commands it contains), you need to first add the executable property (chmod +x script.sh) to the script file, and then run:./script.sh
6. Part V Third Lesson notice
Today's class will come here, together refueling it!
Next lesson we learn: variables in the hand, the shell does not worry
World
Every emotion has a temperature,
Tens of millions of codes seem to have personalities.
Here are the original tutorials, it jungle ...
Explore the program life with you.
I am Shenmon, an embedded software engineer struggling in Paris.
Personal profile
Love life, like swimming, a little understanding of cooking.
Life motto: "Run towards the benchmark"
Linux Discovery Tour | Part V Lesson two: a shell deep like the sea, cool shell love