Preface
Article 1: Super Tools/Terminals, xterms and Shells
1. Super Tools
2. To illustrate the shell, some background knowledge is needed here.
1. Terminals, xterms and Shells
2. Terminals
3、xterms
4、Shells
3. Shell starts
Article 2: Automatically fill up/command line history/edit command line/available shell shortcuts
1. Automatically make up;
2. Command line history
3. Available Shell shortcuts
Chapter 3: Command arrangement/Command task scheduling/Command replacement
1. Arrangement of commands
2. Command task scheduling
3. Replacement of commands
Article 4: File name matching/output redirection
1. File name matching
2. Special characters that quote shell
3. Output redirection
1. Redirect between multiple commands
2. Redirect to file
Article 5: bash configuration file/prompt/change $PATH
1. bash configuration file
2. Prompt
3. Change $PATH
Article 6: Command alias, Shell functions/From here/Shell FAQ
1. Command alias, shell functions
1. Alias for commands
2. Shell function
2. Start from here
About this article
Related Documents
+++++++++++++++++++++++++++++++++++++++++++++++++++++
text
+++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright information
The content of this article comes from the Basics section of MUO, and its original English version is available from /docs. The Chinese version comes from Wu Xiaoguang's CMUO /~xgwu/cmuo/. MUO is a beginner manual provided by Mandrake Linux (/) for users. Its content is practical and updated in real time, making it very suitable for beginners to make reference. Unlike the common Linux tutorials, MUO introduces Linux beginners to methods of learning Linux rather than descriptions of a certain system, which is particularly important for learning various Linux distributions that vary widely.
During the compilation and sorting of this article, the relevant chapters were deleted and modified accordingly, and some content targeting Mandrake Linux was removed.
Preface
Using Shell
The following describes and explains the basic shell commands and mechanisms.
Article 1: Super Tools/Terminals, xterms and Shells
1. Super Tools
You may have heard the argument that the command line is already outdated, that thing is mysterious, etc. Some people even think that these commands should not be available in the operating system.
The truth is, you can use Linux without knowing any shell. After you start the system, you can directly enter X Window and finally shut down under X Window.
I firmly believe that using Linux but not understanding shells is like using first gear when driving. Of course, it seems straightforward and simple at first, and works in most cases. But it's slow and can't really experience the fun of driving.
Yes, the command line is interesting. Just like using a large pile of collected building blocks, you can actually complete many unexpected innovations and some extremely complex tasks, which can be solved in just a few lines of commands. This is because in Unix, shell is not a simple command interpreter (typically DOS in Windows), but a full-featured programming environment.
This doesn't mean that the shell is very easy to learn. You know, good things are a bit harder, and it still takes some time. ;-) But believe me, it is definitely worth it. In a very short time, you can be touted by a large group of laymen as Unix wizard. *grin*
2. To illustrate the shell, some background knowledge is needed here.
1. Terminals, xterms and Shells
Dating back to the time when Unix was born, there was no "personal computer" that is now popular. A machine called a computer or a behemoth of throughput tape and magnetic memory (using the term 'core' to represent system memory). The PDP-11, which was launched by DEC (now Compaq), was small in size (called mini) and low in price, caused a huge response in universities, and many schools were unable to afford a computer until then (PDP-11 was affordable and at only $10,000).
The operating systems of these machines are written in assembly language and machine language, so they are very efficient to run, but they are not unportable. Each computer company equips its machines with a unique operating system and then sells them.
This clumsy approach was quickly realized, so people began to build an operating system that could run on machines of different brands. In 1969, Ken Thompson began writing the first line of code that became Unix. (Thompson once participated in a project: MULTICS, Unix is a joke about it) In fact, things really began after Dennis Ritchie designed a new programming language for this new operating system - C.
Although Unix is not as efficient as the original operating system, it has three outstanding advantages: it can be ported to other machines at will, among which the C language greatly simplifies programming, and these are all free. Soon, universities across the United States were busy starting to install Unix for machines.
2. Terminals
Unix is an operating system that can run on many types of machines, but how do people use these machines? They connect to these machines through dumb terminals, that is, machines composed of keyboards, monitors and sufficient electronics are connected to the central computer. On these terminals, the user can type a character (teletypy), which is the origin of the string 'tty' that indicates the terminal device file and the name of the 'getty' command.
You might ask, where are these things now. The manufacturers of these terminals are unable to meet a final standard, which results in the terminals of each brand having their own keyboard layout, their own way of displaying characters on the screen, what signals to send or receive to represent what characters, control codes, etc.
To avoid these confusions, a capability file with all the different terminal features is created, which is 'termcap'. Use a tool to open '/etc/termcap' and take a look, don't be scared ;-) .
Most Linux terminals use 'vt100' or 'linux' as the terminal type.
3、xterms
In the early 1980s, a Unix graphics subsystem was produced -- the X Window System. In the early 1990s, in order to better implement applications on Intel-based Unix-class systems (such as FreeBSD, NetBSD, and Linux), a system branch was generated - XFree86.
A great benefit in X Window is that it can run multiple virtual terminals. There is even such an application under X Window --'xterm'. You will find that 'xterm' and 'virtual terminal' are the same in many cases. Some places say 'open an xterm', but you don't have to use the 'xterm' program. Other terminal emulators, such as rxvt, konsole, aterm, eterm, wterm, etc., are also effective.
The terminal emulator (also known as a virtual terminal) is connected to the system through a pseudo tty device -- pty and uses its own display standard -- xterm . This leads to small differences between different terminal emulators on some keys or programs depending on how much the simulator complies with the 'xterm' display standards.
4、Shells
In order to run the program in the terminal, a shell is required. The shell is part of the operating system, used to deal with users, and can be used to coordinate individual commands.
The first real Unix shell -- 'sh', also known as 'Bourne shell', was born in 1975 by Steve Bourne . Soon, other shells emerged, such as 'ksh' and 'zsh' based on the original 'Bourne shell', which are often used as standard shells in exclusive Unixes systems; there are also some shells derived from C, such as 'csh' or 'tcsh'.
In Linux, the labeled shell is 'bash', that is, the GNU Bourne-Again Shell (a bit of a joke...). This shell is very powerful (some people even think it is too huge), and the compressed man page has 50 KB.
3. Shell starts
First of all, there is a little explanation: In normal applications, it is recommended that you do not use the 'root' account to run the shell. If you are still a novice, this should be paid special attention to. As an ordinary user, you cannot destroy the system whether you intentionally or unintentionally; but if it is 'root', it's different. Just typing a few letters can lead to catastrophic consequences.
When you log in to the system or open an xterm window, the first thing you see is the prompt (prompt). The standard prompt for Red Hat Linux includes your username, login hostname (if not set, it is 'localhost'), the current directory (working directory), and the prompt symbol:
[tom@belbo tom]$
I log into a host named 'belbo' with username 'tom', currently in my home directory --'/home/tom'. 'root' prompt:
[root@belbo root]#
In addition to different usernames, the prompt symbol changes from '$' to '#'. According to Bourne shell tradition, the prompt for the average user ends with '$', while the super user uses '#'.
Each part of the prompt can be customized and you will have a deeper understanding later.
To run a command, you just type in the command at the prompt and press the key. The shell will search for this command in its path (see details later), run it after it is found, and output the corresponding result (if any) in the terminal. After the command is finished, a new prompt is given:
[tom@belbo tom]$ whoami
tom
[tom@belbo tom]$
By the way, it doesn't matter where the cursor is when you hit ENTER, because the shell always reads the entire line.
The basic commands include: 'ls' (list directory , list directory content), 'cp' (copy , copy), 'mv' (mov / rename , move / rename ), 'cd ' (change directory , change directory ), and these commands can be followed by a bunch of optional options. There is a detailed introduction to man page in this regard (man ls, man mv , etc.).
Here are a few short descriptions of terminology before you set out for the shell territory. The command may have some options and arguments:
mv -i file dir
where '-i' is an option for the command 'mv', while 'file' and 'dir' are parameters. All options are described in detail in the man page of this command (in this case man mv), and the parameters are provided by you. Options determine how the command works, while parameters are used to determine the target of the command's action.
So far, the introduction is a bit like the DOS shell that many people hate and despise, but with the introduction below, you will have a new experience.
Article 2: Automatically fill up/command line history/edit command line/available shell shortcuts
Unix (and successor Linux) was born under the command line, so there are many very practical functions in the command line in Unix. In this article, we will learn more about it in the future.
1. Automatically make up;
How to jump from your current home directory to '/usr/src/redhat/' as fast as possible with 'cd' (change directory, change directory)?
cd /u<TAB>sr<TAB>r<TAB>
This is called "automatic command line completion", which is indispensable in ordinary applications. Let's take a closer look at this example:
cd /u<TAB>
It's very simple to expand to cd /usr/ . The following
cd /u<TAB>sr<TAB>
Extended to cd /usr/src/ . If you only knocked on cd /us, the three subdirectories matching ('cd /u*/s*') under '/usr' will be listed for you to choose from: '/usr/sbin', '/usr/share' and '/usr/src'.
Therefore, the keys can be conveniently used to find matching files or subdirectories based on the first few letters. For example, ls /usr/bin/zip will list all files or subdirectories below '/usr/bin', starting with the string 'zip'. Of course, there are more powerful commands to complete this type of task, but this method is indeed very useful.
In addition, it is particularly convenient when you encounter long file names. Suppose you want to install an RPM package called 'boomshakalakwhizbang-4.6.4.', you enter rpm -i boom . If no other files in the directory can match, the shell will automatically help fill it.
cd /usrl
Expand to cd /usr/src/linux and wait for it to continue. There are two matching directories in '/usr/src': '/usr/src/linux-[...]', '/usr/src/linux'. How to tell the shell the one you want? Just follow a slash (/, slash), and you can choose the one behind.
If you are not sure whether it is '/usr/src/linux/Documentation' or '/usr/src/linux/documentation'. And you know, Linux is case sensitive. If you have read the previous section carefully, you can use:
cd /usrl/d
Extended to '/usr/src/linux/drivers/', so it should be 'Documentation' (capsular 'D').
This complement is also effective for the command:
[tom@belbo tom]$ gre<TAB>
grecord grefer grep
[tom@belbo tom]$ gre
Here the shell will list all known commands starting with the string 'gre'.
2. Command line history
By pressing the Up arrow key, you can go backwards through the commands you have recently entered under the console. Use the downward direction key to traverse forward. If connected to the SHIFT key, you can also iterate through the output in the console. You can also edit the old command and then run it again.
After pressing , the shell enters "reverse-i(ncremental)-search" mode. Now enter the initial letter of the command you are looking for:
(reverse-i-search)`':. Knocking in 'i' may become:
(reverse-i-search)`i': isdnctrl hangup ippp0
If you press the key again, the above command will be executed again. And if you press the Right, Left arrow keys or , the above command will return to the normal command line so that you can edit it appropriately.
Edit the command line
Through the cursor and function keys (Home, End, etc.), you can browse and edit the command line, and if you need it, you can also use keyboard shortcuts to complete the general editing:
l <CTRL k>: Delete the part from the cursor to the end of the line
l <CTRL u>: Delete the part from the cursor to the beginning of the line
l <ALT d>: Delete the part from the cursor to the end of the current word
l <CTRL w>: Delete the part from the cursor to the beginning of the current word
l <CTRL a>: Move the cursor to the beginning of the line
l <CTRL e>: Move the cursor to the end of the line
l <ALT a>: Move the cursor to the head of the current word
l <ALT e>: Move the cursor to the end of the current word
l <CTRL y>: Insert the recently deleted word
l <!$>: Repeat the last parameter of the previous command.
For example: you created a new directory with the command mkdir peter/pan/documents/tinkerbell. Now you use the command 'cd' to enter the directory. You can use cd !$, and the shell will add the parameter of the previous command 'mkdir' to the current 'cd'.
When you dig deeper into Linux, you will see that these shortcuts are sometimes valid when they are entered under other applications, for example, in the input box in the browser.
3. Available Shell shortcuts
Red Hat Linux comes with a few shortcuts, some of which are originally available in bash, while others are pre-set for you (you will see how to set it up later).
Since the home directory is the activity center for every user, many Unix has special shortcuts for this.
'~' is the abbreviation of your home directory. Let's assume that you are in another directory and want to copy a file named 'sometext' to the 'docs' subdirectory under your home directory. In addition to input:
cp sometext /home/myusername/docs
You can also use the abbreviation:
cp sometext ~/docs
In theory, this can also be applied to the command 'cd'. Regardless of where the current path is, cd ~ will return to your home directory. In fact, it can be simplified. Just type cd and you can return to the home directory.
Red Hat Linux provides you with some pre-set shortcuts (called 'alias', aliases) such as:
l ll : Will execute 'ls -l -k' (list directory contents in long format, including some file attributes, and display file size in KB instead of byte)
l ls: Will execute 'ls -F --color=auto' (list directory contents, plus file type identification, and use color)
Now you should have a further understanding of shell and some shortcuts. Let's take a look at what the shell can do besides applying some simple commands.
Chapter 3: Command arrangement/Command task scheduling/Command replacement
1. Arrangement of commands
Now you will see some commonly used command arrangements. You might want to give all the commands in one line and then you can turn your attention elsewhere. No problem, the shell allows you to place special queueing characters between different commands. Here we will introduce the two most commonly used ones.
Note that for the sake of a clearer look, I have added spaces on both sides of these characters. In practical applications, you don't have to do this, the effects of 'ls -a ; du -hs' and 'ls -a;du -hs' are the same.
command1 ; command2
First execute command1 , regardless of whether command1 errors or not, then execute command2 .
For example:
ls -a ; du -hs
Everything in the directory will be listed on the screen, and then the disk sizes occupied by all directories and their subdirectories.
command1 && command2
Command2 is executed only after command1 is run correctly.
For example:
ls -a bogusdir && du -hs
Will return ls: bogusdir: No such file or directory , and 'du' does not run at all (this is because you don't have the 'bogusdir' directory). If you swap the symbol with ';', 'du' will be executed.
In order to further illustrate the difference between ';' and '&&', and the use of general command arrangements, let’s give a classic example: compilation and installation of the Linux kernel.
To compile and install Linux, you need to execute a string of commands: 'make dep', 'make clean', 'make bzImage', 'make modules', 'make modules_install', and 'make install'. If you have to wait for a command to complete, then enter the next one, wait and then enter,..., it will be too troublesome. On the other hand, each command can only start execution after the current command has been executed correctly. If you use ';' to arrange the commands, the subsequent ones will run as usual even if the commands fail to execute. Finally, you may get a problematic kernel image (image) in the '/boot' directory. And use '&&':
make dep && make clean && make bzImage && make modules && make modules_install && make install
You can compile the kernel and its modules without interrupting in the middle and complete the subsequent installation.
2. Command task scheduling
When you run a command or start a program in the terminal, the terminal must wait until the command or program is completed before it can be used again. In Unix, we call such a command or program running in the foreground. If you want to run another command in the terminal, you need to open another new terminal.
But there is a more elegant way here, called jobbing or backgrounding. When you use task scheduling or place commands in the background, the terminal is immediately liberated, so that the terminal can immediately accept new input. To achieve this, you just add a & after the command:
gqview &
Tell the shell to put the image viewer 'GQview' in the background to execute (that is, run as a job).
The command jobs will tell you which commands and programs are running in this terminal window:
jobs
[1]+ Running gqview &
This is important when you want to close the terminal window, because closing the terminal will cause all tasks running there to be aborted, and in this case, if you close the terminal, the GQview program opened by the terminal will also be closed.
But how to put a program run in the foreground in the background? no problem:
gqview
<CTRL z>
[2]+ Stopped gqview
bg
[2]+ gqview &
Key combination will suspend the running program in the terminal, and you can then use the bg command to execute it in the background.
Please note that running graphics applications in the background is sometimes useful, so that the error message of this program can be displayed in the terminal, although this may not be directly helpful to you. When you encounter trouble and ask others, these error prompts will be useful.
Some graphics programs are likely to be in the test period (Beta), and although they are executed in the background, they will also output some information in the terminal. If you are dissatisfied with this, you can use the following command:
command &>/dev/null &
This not only sends the program to the background to execute, but also sends its output to the '/dev/null' file. '/dev/null' is the system's "shredder" (shredder) and all the information sent there will be gone.
3. Replacement of commands
Command substitution is a very practical feature. Let's assume that you want to take a look at the '' file in the XFree86 document, but you don't know where this file is. But you are a clever user, have heard of the 'locate' command and have also installed the 'slocate' package, you can use:
locate
Found that file in '/usr/X11R6/lib/X11/doc'. Now you can use 'less' in the terminal or go to that directory in the file manager and read the file. And command replacement can bring you some convenience:
less $(locate )
In place in one step. The output of the command 'locate' (= /usr/X11R6/lib/X11/doc/) is used as the parameter of 'less', and then the file content can be displayed.
The syntax of this mechanism is:
command1 $(command2)
In addition to '$( )', you can also use backquote:
command1 `command2`
This reduces input, but is poorly readable and is easily confused with general single quotes without replacement functions. I appreciate the former method more, but it's up to you in the end.
Here is another example. Let's assume that you intend to end a program called 'rob'. You must first use the command 'pidof' to find the corresponding process number (Process ID), and then use this PID as a parameter to run the 'kill' command, so that you can end the 'rob' program. In addition to using:
pidof rob
567
kill 567
You can also try:
kill `pidof rob`
How about it, has the efficiency improved?
In the next article, I will introduce two other practical mechanisms of shell: file name matching and output redirection.
Article 4: File name matching/output redirection
1. File name matching
File name matching allows you to specify multiple files without having to write out the names one by one. You will use some special characters, called wildcards.
Suppose you want to use the 'rm' command to delete all files ending with the string '.bak' in the directory. In addition to following 'rm' with all file names as arguments, you can also use the wildcard '*':
rm *.bak
'*' can match one or more characters. In this example, you tell the shell to extend the parameters of the command 'rm' to "all files ending with '*.bak'", and the shell tells the extended parameters of the shell to tell the 'rm' command.
You will see that the shell will read and interpret the command line before the command is executed. It is because of this that you can use wildcards in arguments to shell commands.
Let's go further to understand the wildcard '*'. Suppose you have a directory containing files '', '' and ''. You want to keep only the files '', you can use:
rm *4*.bak
The shell expands '*4*.bak' into "all strings with '4' and ends with '.bak'".
Note that rm 4*.bak does not work because this matches files starting with '4'. Since there is no such file in the directory, the shell expands this pattern to an empty string, so 'rm' will return an error message:
rm: cannot remove `4*.bak': No such file or directory
If you want to keep the file '', while deleting '' and ''. This seems a bit difficult because the name of the deleted file is different except for the suffix. But luckily, you can specify the file with no:
rm *[!6].bak
This will be read as: except for files ending with '', delete all other files ending with '.bak'. You must put the negation sign and the inverse character (here is 6) in brackets, otherwise the shell will interpret the exclamation mark as the beginning of a history substitution. Taking the inverse is valid in all matching patterns introduced in this article.
Please note: the wildcard '*' is used in conjunction with the inverse sign, which can easily cause problems. Guess
rm *[!6]*.bak
What does it mean? This command will delete all files, even files with '6' in their name. If you put the wildcard '*' before and after the inverse, actually taking the inverse will fail because the shell interprets it as "a file that does not contain that character anywhere in all names". In our case, only the files'' do not conform to this pattern.
The second wildcard is the question mark: '?'. When matching, a question mark can only represent one character. To demonstrate its purpose, we add two new files to the assumption in the above example: '~' and ''. Now list all files with four characters after the dot:
ls *.????
The question mark wildcard can effectively avoid the above-mentioned "negation trap" (negation trap):
rm *[!4]?.*
It will be expanded to "all files except the penultimate character before the dot is '4'", that is, only files are retained ''.
You might ask, are there any other ways to match? So far you have only seen ways to match unique characters at the specified location. But you can do this too:
ls [13]*
All files starting with the characters '1' or '3' will be listed; in our case, the files '', '~' and '' match. Note that you have to enclose the matching patterns in brackets, otherwise the patterns only match files starting with the string '13'.
Next, you will be happy to see that you can also define the range of matches:
ls *[3-8]?.*
The file that lists all the penultimate characters before all dots fall into the range '3' to '8'. In our example, the matching files are '' and ''.
2. Special characters that quote shell
However, the above mechanisms have one disadvantage: the shell always tries to expand before the command is executed. Sometimes, it can get tricky:
l The file name contains special characters. Suppose you have a file named '!' in that directory. The following is an attempt to match the pattern:
rm !*
rm
rm: too few arguments
The shell interprets '!*' as a replacement for history (adding all parameters of the previous command), rather than a matching method.
l The command itself takes special characters as parameters. Some command-line tools under Linux, such as (e)grep, sed, awk, find and locate, use their own regular expressions. These expressions look surprisingly similar to pattern matching, but differ in some places.
But in order for these special commands to take effect, the shell cannot first explain them as pattern matching:
find . -name [1-9]* -print
find: paths must precede expression
It should be:
find . -name '[1-9]*' -print
./
./
./
./~
You can refer to special characters through backslash, such as ! , $ , ? or space:
ls \!*
!
Or use (single) quotes:
ls '!'*
!
Please note that you should see clearly where the quotes should be placed. The command ls '!*' will look for a file named '!*', because the wildcard is also in quotes, so it can only be explained literally.
3. Output redirection
The philosophy of Unix is to bring together many applets, each with special expertise. Complex tasks are not completed by large software, but are completed by using shell mechanisms and combining many mini programs. Redirection plays an important role in this.
1. Redirect between multiple commands
This is determined by pipes, and is marked by pipe symbols. The syntax is:
command1 | command2 | command3 etc.
You must have seen this format. Pipelines often send the output of a program to 'more' or 'less' to read.
ls -l | less
Among them, the first command provides the directory contents, and the second displays it as a page turn. More complex examples such as:
rpm -qa | grep ^x | less
The first command gives all installed RPM packages, the second filters them (filter: 'grep'), leaving only packages starting with '^x', and the third command displays the results as page-turning.
2. Redirect to file
Sometimes, you want to save the output of the command to a file, or take the contents of the file as an argument to the command. This can be achieved through '>' and '<'.
command > file
Save the output of command to file, which overwrites the contents in the file:
ls > dirlist
Save the contents of the current directory to the 'dirlist' file.
command < file
Take the file content as input to command:
sort < dirlist > sdirlist
Send the contents of the file 'dirlist' to the command 'sort', and then send the sorted results to the file 'sdirlist'. Of course, you can also get it in one step:
ls | sort > sdirlist
A special way is 'command 2> file'. This sends the command execution error message to the file. You will need this at that time...
Another type of operator is '>>', which adds the output to an existing file:
echo "string" >> file
Add string to file. This is a good way to complete editing without opening the file!
However, both the '<' and '>' operators have an important limitation:
command < file1 > file1
The content of file1 will be deleted, and
command < file1 >> file1
But it works well, adding the processed file1 content back to the file.
Isn't it a little too much? ;-) Don’t panic, you can learn step by step at your own speed. Don't forget that practice is the best way to learn...
After knowing the mechanisms of many shells, you may be anxious to know how to customize your environment. In the next two articles, you will get inspiration in this regard. In the last article, there is also a FAQ on how to handle shell error messages and some configuration tips.
Article 5: bash configuration file/prompt/change $PATH
1. bash configuration file
In your home directory, run
ls .bash*
You will see these files:
l.bash_history: records the command you entered before,
l.bash_logout: The command to be executed when you exit the shell,
l.bash_profile: The command to execute when you log in to the shell,
l.bashrc: The command to be executed every time a new shell is opened.
Note the difference between the latter two: '.bash_profile' is read only once at the beginning of the session, while '.bashrc' is read every time a new terminal (such as a new xterm window) is opened. By tradition, you have to put defined variables, such as PATH, into '.bash_profile', and like aliases (alias) and functions, in '.bashrc'. But since '.bash_profile' is often set to read the content of '.bashrc' first, if you want to save trouble, put all configurations into '.bashrc'.
These files are the settings for each user. System-level settings are stored in files under '/etc/profile', '/etc/bashrc' and directory '/etc/'. But you have to get used to using their own configuration files: editing does not require 'root' permission, and it can also make your settings more personalized. When the system level conflicts with the user level settings, the user's settings will be adopted.
Read the content of '.bashrc', if you want to save some trouble, put all your configuration into '.bashrc'.
The above files are the settings of each user, and the system-level settings are stored in files under '/etc/profile', '/etc/bashrc' and directory '/etc/'. You'd better get used to using your own configuration files: editing does not require 'root' permission, and it can also make your settings more personal. When there is a conflict between the system level and the user level settings, the user's settings will be preferred.
2. Prompt
Every time you open a console or xterm, the first thing you see is the prompt (prompt), similar to:
account@hostname ~ $
By default, the prompt will display your username, hostname (default is 'localhost'), and the current directory (in Unix, '~' means your home directory).
By tradition, the last character can identify whether you are a normal user ($), or 'root' (#).
You can set the prompt via the $PS1 variable. Order
echo $PS1
The current settings will be displayed. The meaning of the available characters is explained in the 'PROMPTING' section of man bash.
How can I complete the ideal setup? For forgetful beginners, the default setting is a bit unfriendly, because the prompt only displays the last part of the current directory. If you see a prompt like this
tom@localhost bin $
Your current directory may be '/bin', '/usr/bin', '/usr/local/bin' and '/usr/X11R6/bin'. Of course, you can use
pwd (output the current directory, print working directory)
Can you call the shell to automatically tell you the current directory?
sure. The settings I will mention here, including the prompt, are mostly included in the file '/etc/bashrc'. You can change the settings by editing '.bash_profile' and '.bashrc' in their respective home directories.
In the 'PROMPTING' section in man bash, these parameters are explained in detail. You can add some gadgets such as the current time in different formats, the history number of the command, and even different colors.
In '~/.bashrc', my favorite settings are:
PS1="\[\033[1m\][\w]\[\033[0m\] "
The setting of 'root' in '~/.bashrc' is:
PS1="\[\033[0;31m\][\w]\[\033[0m\] "
This way the prompt I get is:
[/usr/bin]
When using 'root', it becomes:
[/usr/bin]
I've removed the hostname and username because I don't need that. But first of all, I can tell whether my identity is an ordinary user or a 'root' at a glance. Note that the prompt for ordinary users can be in black and white characters, or in white characters.
To get the appropriate color configuration on the terminal, you can edit the following script color, give execution permissions (chmod +x color), and then run it.
#!/bin/bash
#
# This file echoes a bunch of color codes to the
# terminal to demonstrate what's available. Each
# line is the color code of one forground color,
# out of 17 (default + 16 escapes), followed by a
# test use of that color on all nine background
# colors (default + 8 escapes).
#
T='gYw' # The test text
echo -e "\n 40m 41m 42m 43m\
44m 45m 46m 47m";
for FGs in ' m' ' 1m' ' 30m' '1;30m' ' 31m' '1;31m' ' 32m' \
'1;32m' ' 33m' '1;33m' ' 34m' '1;34m' ' 35m' '1;35m' \
' 36m' '1;36m' ' 37m' '1;37m';
do FG=${FGs// /}
echo -en " $FGs \033[$FG $T "
for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
do echo -en "$EINS \033[$FG\033[$BG $T \033[0m";
done
echo;
done
echo
A more appropriate setting:
PS1="\u: \w\\$ "
In this way, the prompt becomes:
user_name: /usr/bin$
You can test different settings by using the command export (for example, export PS1="\u: \w\\$ "). If you find a suitable prompt, put the settings into your '.bashrc''. This will take effect every time the console or terminal window is opened.
You can even set the theme to the prompt, i.e. match it with different colors to make it look like a great one.
C64 prompt. If you are interested in this, you can take a look
Bashish( /arnognulf/ )。
3. Change $PATH
'$PATH' is the same as '$PS1', and is an environment variable. enter
set
All currently defined environment variables will be listed.
The environment variables you see are defined in the shell's configuration file, which may be the user's own configuration file, or may be defined by 'root' through the system-level file below '/etc'. If you use X, some more variables will be configured by X, your window manager, or the startup file of your desktop environment.
If you are not very clear about these settings, it is best not to change them casually for the time being. It is useful to know how to change the $PATH variable because this variable determines which directories the shell will look for commands or programs. If the directory of the command to be executed is in $PATH, you don't have to enter the full path of this command, just enter the command. Some third-party software does not place executable files into the standard Linux directory. Therefore, adding these non-standard installation directories to $PATH is a solution. Additionally, you will see how to deal with general environment variables.
First, as a convention, all environment variable names are capitalized. Since Linux is case sensitive, you should be careful about this. Of course, you can define some variables yourself, such as '$path', '$pAtH', but the shell ignores them.
The second point is that variable names sometimes start with '$', but sometimes they are not. When setting a variable, you use the name directly without adding '$':
PATH=/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin
To get the value of a variable, you must add '$' before the variable name:
echo $PATH
/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin
Otherwise, the variable name will be treated as normal text:
echo PATH
PATH
The third thing to note when dealing with $PATH variables is that you cannot just replace the variables, but add the new string to the original value. In most cases you can't use 'PATH=/some/directory' because this will remove all other directories in $PATH so that you have to give the full path when you run the program in that terminal. Therefore, only add:
PATH=$PATH:/some/directory
In this way, PATH is set to the current value (denoted by $PATH) + the newly added directory.
So far, you have only set a new $PATH variable for the current terminal. If you open a new terminal and run echo $PATH , the old $PATH value will be returned without seeing the new directory you just added. Because you previously defined a local environment variable (only to the current terminal).
To define a global variable to take effect in a later opened terminal, you need to output the local variable (export), you can use the 'export' command:
export PATH=$PATH:/some/directory
Now if you open a new terminal, enter echo $PATH and you can see the newly set $PATH. Please note that the command 'export' can only change the variables in the current terminal and the terminals running later. No effect on the terminal that is already running.
To permanently add the directory to your $PATH , just add that line of 'export' to your '.bash_profile' file.
Please do not set PATH in '.bashrc', otherwise it will cause unexpected growth of directories in PATH. Every time you open a new shell, '.bashrc' will work. So if you add a directory to the file, each time you open a terminal, the directory will be added again. This will cause the PATH variable to continue to grow due to directory copying.
Article 6: Command alias, Shell functions/From here/Shell FAQ
1. Command alias, shell functions
Remember all the commands and the options they come with, and then type them one by one at a time, which is really a bit boring. But luckily, you can define shortcuts for common commands. These shortcuts can be defined with simpler command alias or more complex shell functions syntax.
1. Alias for commands
For example, I use the following command to upload a file in MUO:
rsync -e ssh -z -t -r -vv --progress /home/tom/web/muo/rsmuo/docs muo:/www/mandrakeuser/docs
Obviously, if I had to enter one by one every time, I would sooner or later turn into wood. So I defined the alias in '~/.bashrc':
alias upmuo='rsync -e ssh -z -t -r -vv --progress /home/tom/web/muo/rsmuo/docs muo:/www/mandrakeuser/docs'
Now, I just need to type upmuo to complete the upload task.
The syntax for defining an alias is:
alias shortcut='command'
If there are spaces in the command, you need to use quotes (such as spaces between the command and the optional). Note that you can use single or double quotes, but they are different.
Single quotes will strip all characters from the special meaning, while '$' (parameter replacement) and '`' (command replacement) in double quotes are exceptions. This means that if you want to apply a replacement of variables or commands in an alias, you have to use double quotes. Looking at the example above, I defined a variable called MUOHOME in '.bashrc':
export MUOHOME=$HOME/web/muo/rsmuo/docs
To use this variable in the alias above, I have to use double quotes:
alias upmuo="rsync -e ssh -z -t -r -vv --progress $MUOHOME muo:/www/mandrakeuser/docs"
Otherwise, the alias will look for a directory or file named '$MUOHOME'.
You can use 'alias' to quickly create alias on the command line, or put the commands in their respective '~/.bashrc', or put them in the system-level '/etc//' (and in Mandrake Linux 8 before, '/etc/bashrc' was used). To delete an alias, just type: unalias alias . Running alias will list all the alias defined in your system.
If you look at '~/.bashrc' and '/etc//', you will find that the system has some alias defined. You can define multiple aliases for the same command. Of course, you have to confirm that the alias is different from other program names, such as alias rm='ls -l', which does not work. You can enter these shortcuts on the command line and test it out. If the shell cannot find a command with the same name, you can use it as an alias.
The following alias may be useful (don't forget the quotes!):
l alias rpmq='rpm -qa | grep' : Now rpmq string will list all installed RPM packages with string in their names,
l alias ls='ls -ho --color | more' : ls will list files in color paging, the file size is in KB.
l alias use='du --max-depth=1 | sort -n | more' :use Arrange subdirectories by size and list them in pagination.
The alias of the directory can also be removable media: alias dlm='/mnt/cdrom/RedHat/RPMS/' .
Tip: Aliases with similar functions will start with the same letter, such as starting with 'd' for all directories, which will help memorize.
I believe you will use these features.
2. Shell function
Writing shell functions involves shell scripts, which is beyond the scope of our discussion (not within my grasp ;-)). In fact, shell functions belong to shell scripts, but can be preloaded and executed under the same shell (while a general shell script must open at least one sub-shell).
With shell functions, you can do a lot of things that aliases cannot do. Here is an example:
function apros() { apropos $1 | egrep -v '(3|\(n\)'; }
A new command is defined, called 'apros'. apros name will first execute 'apropos name' (i.e. search for the command in the man page), then send the obtained output to the pipeline (|), then filter with 'egrep' to exclude the man page in chapters '3' and 'n'. This command may not be of great use, but you can organize the output of the 'apropos' command.
Functions allow you to use runtime parameters anywhere inside the function. As for the alias, only one parameter is allowed at the end of the command line (such as the previous alias 'rpmq').
'$1' is the positional parameter, which represents the position identifier of the first parameter of the function. And so on, there are '$2' and so on.
function apros() { apropos $1 | egrep -v "\($2"; }
If you run the 'apros' command like this:
apros name man_section_number
This command will search for man pages with name in the title, but exclude the man_section_number section:
apros menu 3
Search for man page with the title 'menu', but excludes chapter 3 (about programming). Notice that you have to quote twice, and you also use double quotes:
l You must refer to the search pattern of 'egrep' so that it will not be misunderstood by the shell.
l You must use double quotes so that the second parameter can be interpreted correctly.
l You must refer to parentheses so that 'egrep' treats the parameters literally.
Isn't it interesting? ;-)
The shell function handles similarly to aliases: put it in your '.bashrc' file so it will take effect permanently.
2. Start from here
All we are talking about is the beginning of the shell. With the shell script mastered, you can do many things, such as automating tasks, correcting errors in other people's scripts, and customizing Linux systems as you are used to. If you are planning to learn some complex programming language, shell scripting is also a good start, because the basic concepts are similar.
BASH Programming - Introduction HOW-TO:
/mdw/HOWTO/
Will go deeper into these topics and will take you to the world of shell programming. Then you can continue reading the Advanced Bash-Scripting Guide ( /mdw/LDP/abs/html/ ) that I highly recommend, by: Mendel Cooper.
If you prefer paper books, I recommend "Teach Yourself Shell Programming" by S. Veeraraghavan, Sams Press. I think O'Reilly's company Learning the bash Shell by Newham/Rosenblatt, but I may only see this ;-).
In addition to these, it is practice, practice, and practice. Read shell scripts written by others to see what they are doing, how they do it, and why they do it that way.
Please do not test your script with 'root'. Have fun .
About this article
Brother flaboy posted it in the forum SHELL discussion area when he compiled it. It was posted as a form of SHELL basic textbook. When he compiled it, he "did the relevant chapters be deleted and modified accordingly when compiling this article, and some content targeting Mandrake Linux were removed."
I saw that this document is very good, so I sorted it out again and adjusted the structure of the document. According to the content of the document, I appropriately added the serial number and made a directory, mainly to facilitate everyone to read; I thank the original author and Chinese translator, and also thank Brother Flaboy for his organization;
It is also a happier thing for me to organize documents. At least when I read the documents, I can know what is more important and get what I want to learn, so I will always organize documents; if time allows and have the ability, I will also write some. ──North, South, North
There is no technical content in organizing documents, so why do you do it?
Although there is no technical content, I think if it can bring a little convenience to others, I think what I have done is worth it. Compared with the original creators and Chinese translators, what is what I have done?
──North, South, North
Article 1: Super Tools/Terminals, xterms and Shells
1. Super Tools
2. To illustrate the shell, some background knowledge is needed here.
1. Terminals, xterms and Shells
2. Terminals
3、xterms
4、Shells
3. Shell starts
Article 2: Automatically fill up/command line history/edit command line/available shell shortcuts
1. Automatically make up;
2. Command line history
3. Available Shell shortcuts
Chapter 3: Command arrangement/Command task scheduling/Command replacement
1. Arrangement of commands
2. Command task scheduling
3. Replacement of commands
Article 4: File name matching/output redirection
1. File name matching
2. Special characters that quote shell
3. Output redirection
1. Redirect between multiple commands
2. Redirect to file
Article 5: bash configuration file/prompt/change $PATH
1. bash configuration file
2. Prompt
3. Change $PATH
Article 6: Command alias, Shell functions/From here/Shell FAQ
1. Command alias, shell functions
1. Alias for commands
2. Shell function
2. Start from here
About this article
Related Documents
+++++++++++++++++++++++++++++++++++++++++++++++++++++
text
+++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright information
The content of this article comes from the Basics section of MUO, and its original English version is available from /docs. The Chinese version comes from Wu Xiaoguang's CMUO /~xgwu/cmuo/. MUO is a beginner manual provided by Mandrake Linux (/) for users. Its content is practical and updated in real time, making it very suitable for beginners to make reference. Unlike the common Linux tutorials, MUO introduces Linux beginners to methods of learning Linux rather than descriptions of a certain system, which is particularly important for learning various Linux distributions that vary widely.
During the compilation and sorting of this article, the relevant chapters were deleted and modified accordingly, and some content targeting Mandrake Linux was removed.
Preface
Using Shell
The following describes and explains the basic shell commands and mechanisms.
Article 1: Super Tools/Terminals, xterms and Shells
1. Super Tools
You may have heard the argument that the command line is already outdated, that thing is mysterious, etc. Some people even think that these commands should not be available in the operating system.
The truth is, you can use Linux without knowing any shell. After you start the system, you can directly enter X Window and finally shut down under X Window.
I firmly believe that using Linux but not understanding shells is like using first gear when driving. Of course, it seems straightforward and simple at first, and works in most cases. But it's slow and can't really experience the fun of driving.
Yes, the command line is interesting. Just like using a large pile of collected building blocks, you can actually complete many unexpected innovations and some extremely complex tasks, which can be solved in just a few lines of commands. This is because in Unix, shell is not a simple command interpreter (typically DOS in Windows), but a full-featured programming environment.
This doesn't mean that the shell is very easy to learn. You know, good things are a bit harder, and it still takes some time. ;-) But believe me, it is definitely worth it. In a very short time, you can be touted by a large group of laymen as Unix wizard. *grin*
2. To illustrate the shell, some background knowledge is needed here.
1. Terminals, xterms and Shells
Dating back to the time when Unix was born, there was no "personal computer" that is now popular. A machine called a computer or a behemoth of throughput tape and magnetic memory (using the term 'core' to represent system memory). The PDP-11, which was launched by DEC (now Compaq), was small in size (called mini) and low in price, caused a huge response in universities, and many schools were unable to afford a computer until then (PDP-11 was affordable and at only $10,000).
The operating systems of these machines are written in assembly language and machine language, so they are very efficient to run, but they are not unportable. Each computer company equips its machines with a unique operating system and then sells them.
This clumsy approach was quickly realized, so people began to build an operating system that could run on machines of different brands. In 1969, Ken Thompson began writing the first line of code that became Unix. (Thompson once participated in a project: MULTICS, Unix is a joke about it) In fact, things really began after Dennis Ritchie designed a new programming language for this new operating system - C.
Although Unix is not as efficient as the original operating system, it has three outstanding advantages: it can be ported to other machines at will, among which the C language greatly simplifies programming, and these are all free. Soon, universities across the United States were busy starting to install Unix for machines.
2. Terminals
Unix is an operating system that can run on many types of machines, but how do people use these machines? They connect to these machines through dumb terminals, that is, machines composed of keyboards, monitors and sufficient electronics are connected to the central computer. On these terminals, the user can type a character (teletypy), which is the origin of the string 'tty' that indicates the terminal device file and the name of the 'getty' command.
You might ask, where are these things now. The manufacturers of these terminals are unable to meet a final standard, which results in the terminals of each brand having their own keyboard layout, their own way of displaying characters on the screen, what signals to send or receive to represent what characters, control codes, etc.
To avoid these confusions, a capability file with all the different terminal features is created, which is 'termcap'. Use a tool to open '/etc/termcap' and take a look, don't be scared ;-) .
Most Linux terminals use 'vt100' or 'linux' as the terminal type.
3、xterms
In the early 1980s, a Unix graphics subsystem was produced -- the X Window System. In the early 1990s, in order to better implement applications on Intel-based Unix-class systems (such as FreeBSD, NetBSD, and Linux), a system branch was generated - XFree86.
A great benefit in X Window is that it can run multiple virtual terminals. There is even such an application under X Window --'xterm'. You will find that 'xterm' and 'virtual terminal' are the same in many cases. Some places say 'open an xterm', but you don't have to use the 'xterm' program. Other terminal emulators, such as rxvt, konsole, aterm, eterm, wterm, etc., are also effective.
The terminal emulator (also known as a virtual terminal) is connected to the system through a pseudo tty device -- pty and uses its own display standard -- xterm . This leads to small differences between different terminal emulators on some keys or programs depending on how much the simulator complies with the 'xterm' display standards.
4、Shells
In order to run the program in the terminal, a shell is required. The shell is part of the operating system, used to deal with users, and can be used to coordinate individual commands.
The first real Unix shell -- 'sh', also known as 'Bourne shell', was born in 1975 by Steve Bourne . Soon, other shells emerged, such as 'ksh' and 'zsh' based on the original 'Bourne shell', which are often used as standard shells in exclusive Unixes systems; there are also some shells derived from C, such as 'csh' or 'tcsh'.
In Linux, the labeled shell is 'bash', that is, the GNU Bourne-Again Shell (a bit of a joke...). This shell is very powerful (some people even think it is too huge), and the compressed man page has 50 KB.
3. Shell starts
First of all, there is a little explanation: In normal applications, it is recommended that you do not use the 'root' account to run the shell. If you are still a novice, this should be paid special attention to. As an ordinary user, you cannot destroy the system whether you intentionally or unintentionally; but if it is 'root', it's different. Just typing a few letters can lead to catastrophic consequences.
When you log in to the system or open an xterm window, the first thing you see is the prompt (prompt). The standard prompt for Red Hat Linux includes your username, login hostname (if not set, it is 'localhost'), the current directory (working directory), and the prompt symbol:
[tom@belbo tom]$
I log into a host named 'belbo' with username 'tom', currently in my home directory --'/home/tom'. 'root' prompt:
[root@belbo root]#
In addition to different usernames, the prompt symbol changes from '$' to '#'. According to Bourne shell tradition, the prompt for the average user ends with '$', while the super user uses '#'.
Each part of the prompt can be customized and you will have a deeper understanding later.
To run a command, you just type in the command at the prompt and press the key. The shell will search for this command in its path (see details later), run it after it is found, and output the corresponding result (if any) in the terminal. After the command is finished, a new prompt is given:
[tom@belbo tom]$ whoami
tom
[tom@belbo tom]$
By the way, it doesn't matter where the cursor is when you hit ENTER, because the shell always reads the entire line.
The basic commands include: 'ls' (list directory , list directory content), 'cp' (copy , copy), 'mv' (mov / rename , move / rename ), 'cd ' (change directory , change directory ), and these commands can be followed by a bunch of optional options. There is a detailed introduction to man page in this regard (man ls, man mv , etc.).
Here are a few short descriptions of terminology before you set out for the shell territory. The command may have some options and arguments:
mv -i file dir
where '-i' is an option for the command 'mv', while 'file' and 'dir' are parameters. All options are described in detail in the man page of this command (in this case man mv), and the parameters are provided by you. Options determine how the command works, while parameters are used to determine the target of the command's action.
So far, the introduction is a bit like the DOS shell that many people hate and despise, but with the introduction below, you will have a new experience.
Article 2: Automatically fill up/command line history/edit command line/available shell shortcuts
Unix (and successor Linux) was born under the command line, so there are many very practical functions in the command line in Unix. In this article, we will learn more about it in the future.
1. Automatically make up;
How to jump from your current home directory to '/usr/src/redhat/' as fast as possible with 'cd' (change directory, change directory)?
cd /u<TAB>sr<TAB>r<TAB>
This is called "automatic command line completion", which is indispensable in ordinary applications. Let's take a closer look at this example:
cd /u<TAB>
It's very simple to expand to cd /usr/ . The following
cd /u<TAB>sr<TAB>
Extended to cd /usr/src/ . If you only knocked on cd /us, the three subdirectories matching ('cd /u*/s*') under '/usr' will be listed for you to choose from: '/usr/sbin', '/usr/share' and '/usr/src'.
Therefore, the keys can be conveniently used to find matching files or subdirectories based on the first few letters. For example, ls /usr/bin/zip will list all files or subdirectories below '/usr/bin', starting with the string 'zip'. Of course, there are more powerful commands to complete this type of task, but this method is indeed very useful.
In addition, it is particularly convenient when you encounter long file names. Suppose you want to install an RPM package called 'boomshakalakwhizbang-4.6.4.', you enter rpm -i boom . If no other files in the directory can match, the shell will automatically help fill it.
cd /usrl
Expand to cd /usr/src/linux and wait for it to continue. There are two matching directories in '/usr/src': '/usr/src/linux-[...]', '/usr/src/linux'. How to tell the shell the one you want? Just follow a slash (/, slash), and you can choose the one behind.
If you are not sure whether it is '/usr/src/linux/Documentation' or '/usr/src/linux/documentation'. And you know, Linux is case sensitive. If you have read the previous section carefully, you can use:
cd /usrl/d
Extended to '/usr/src/linux/drivers/', so it should be 'Documentation' (capsular 'D').
This complement is also effective for the command:
[tom@belbo tom]$ gre<TAB>
grecord grefer grep
[tom@belbo tom]$ gre
Here the shell will list all known commands starting with the string 'gre'.
2. Command line history
By pressing the Up arrow key, you can go backwards through the commands you have recently entered under the console. Use the downward direction key to traverse forward. If connected to the SHIFT key, you can also iterate through the output in the console. You can also edit the old command and then run it again.
After pressing , the shell enters "reverse-i(ncremental)-search" mode. Now enter the initial letter of the command you are looking for:
(reverse-i-search)`':. Knocking in 'i' may become:
(reverse-i-search)`i': isdnctrl hangup ippp0
If you press the key again, the above command will be executed again. And if you press the Right, Left arrow keys or , the above command will return to the normal command line so that you can edit it appropriately.
Edit the command line
Through the cursor and function keys (Home, End, etc.), you can browse and edit the command line, and if you need it, you can also use keyboard shortcuts to complete the general editing:
l <CTRL k>: Delete the part from the cursor to the end of the line
l <CTRL u>: Delete the part from the cursor to the beginning of the line
l <ALT d>: Delete the part from the cursor to the end of the current word
l <CTRL w>: Delete the part from the cursor to the beginning of the current word
l <CTRL a>: Move the cursor to the beginning of the line
l <CTRL e>: Move the cursor to the end of the line
l <ALT a>: Move the cursor to the head of the current word
l <ALT e>: Move the cursor to the end of the current word
l <CTRL y>: Insert the recently deleted word
l <!$>: Repeat the last parameter of the previous command.
For example: you created a new directory with the command mkdir peter/pan/documents/tinkerbell. Now you use the command 'cd' to enter the directory. You can use cd !$, and the shell will add the parameter of the previous command 'mkdir' to the current 'cd'.
When you dig deeper into Linux, you will see that these shortcuts are sometimes valid when they are entered under other applications, for example, in the input box in the browser.
3. Available Shell shortcuts
Red Hat Linux comes with a few shortcuts, some of which are originally available in bash, while others are pre-set for you (you will see how to set it up later).
Since the home directory is the activity center for every user, many Unix has special shortcuts for this.
'~' is the abbreviation of your home directory. Let's assume that you are in another directory and want to copy a file named 'sometext' to the 'docs' subdirectory under your home directory. In addition to input:
cp sometext /home/myusername/docs
You can also use the abbreviation:
cp sometext ~/docs
In theory, this can also be applied to the command 'cd'. Regardless of where the current path is, cd ~ will return to your home directory. In fact, it can be simplified. Just type cd and you can return to the home directory.
Red Hat Linux provides you with some pre-set shortcuts (called 'alias', aliases) such as:
l ll : Will execute 'ls -l -k' (list directory contents in long format, including some file attributes, and display file size in KB instead of byte)
l ls: Will execute 'ls -F --color=auto' (list directory contents, plus file type identification, and use color)
Now you should have a further understanding of shell and some shortcuts. Let's take a look at what the shell can do besides applying some simple commands.
Chapter 3: Command arrangement/Command task scheduling/Command replacement
1. Arrangement of commands
Now you will see some commonly used command arrangements. You might want to give all the commands in one line and then you can turn your attention elsewhere. No problem, the shell allows you to place special queueing characters between different commands. Here we will introduce the two most commonly used ones.
Note that for the sake of a clearer look, I have added spaces on both sides of these characters. In practical applications, you don't have to do this, the effects of 'ls -a ; du -hs' and 'ls -a;du -hs' are the same.
command1 ; command2
First execute command1 , regardless of whether command1 errors or not, then execute command2 .
For example:
ls -a ; du -hs
Everything in the directory will be listed on the screen, and then the disk sizes occupied by all directories and their subdirectories.
command1 && command2
Command2 is executed only after command1 is run correctly.
For example:
ls -a bogusdir && du -hs
Will return ls: bogusdir: No such file or directory , and 'du' does not run at all (this is because you don't have the 'bogusdir' directory). If you swap the symbol with ';', 'du' will be executed.
In order to further illustrate the difference between ';' and '&&', and the use of general command arrangements, let’s give a classic example: compilation and installation of the Linux kernel.
To compile and install Linux, you need to execute a string of commands: 'make dep', 'make clean', 'make bzImage', 'make modules', 'make modules_install', and 'make install'. If you have to wait for a command to complete, then enter the next one, wait and then enter,..., it will be too troublesome. On the other hand, each command can only start execution after the current command has been executed correctly. If you use ';' to arrange the commands, the subsequent ones will run as usual even if the commands fail to execute. Finally, you may get a problematic kernel image (image) in the '/boot' directory. And use '&&':
make dep && make clean && make bzImage && make modules && make modules_install && make install
You can compile the kernel and its modules without interrupting in the middle and complete the subsequent installation.
2. Command task scheduling
When you run a command or start a program in the terminal, the terminal must wait until the command or program is completed before it can be used again. In Unix, we call such a command or program running in the foreground. If you want to run another command in the terminal, you need to open another new terminal.
But there is a more elegant way here, called jobbing or backgrounding. When you use task scheduling or place commands in the background, the terminal is immediately liberated, so that the terminal can immediately accept new input. To achieve this, you just add a & after the command:
gqview &
Tell the shell to put the image viewer 'GQview' in the background to execute (that is, run as a job).
The command jobs will tell you which commands and programs are running in this terminal window:
jobs
[1]+ Running gqview &
This is important when you want to close the terminal window, because closing the terminal will cause all tasks running there to be aborted, and in this case, if you close the terminal, the GQview program opened by the terminal will also be closed.
But how to put a program run in the foreground in the background? no problem:
gqview
<CTRL z>
[2]+ Stopped gqview
bg
[2]+ gqview &
Key combination will suspend the running program in the terminal, and you can then use the bg command to execute it in the background.
Please note that running graphics applications in the background is sometimes useful, so that the error message of this program can be displayed in the terminal, although this may not be directly helpful to you. When you encounter trouble and ask others, these error prompts will be useful.
Some graphics programs are likely to be in the test period (Beta), and although they are executed in the background, they will also output some information in the terminal. If you are dissatisfied with this, you can use the following command:
command &>/dev/null &
This not only sends the program to the background to execute, but also sends its output to the '/dev/null' file. '/dev/null' is the system's "shredder" (shredder) and all the information sent there will be gone.
3. Replacement of commands
Command substitution is a very practical feature. Let's assume that you want to take a look at the '' file in the XFree86 document, but you don't know where this file is. But you are a clever user, have heard of the 'locate' command and have also installed the 'slocate' package, you can use:
locate
Found that file in '/usr/X11R6/lib/X11/doc'. Now you can use 'less' in the terminal or go to that directory in the file manager and read the file. And command replacement can bring you some convenience:
less $(locate )
In place in one step. The output of the command 'locate' (= /usr/X11R6/lib/X11/doc/) is used as the parameter of 'less', and then the file content can be displayed.
The syntax of this mechanism is:
command1 $(command2)
In addition to '$( )', you can also use backquote:
command1 `command2`
This reduces input, but is poorly readable and is easily confused with general single quotes without replacement functions. I appreciate the former method more, but it's up to you in the end.
Here is another example. Let's assume that you intend to end a program called 'rob'. You must first use the command 'pidof' to find the corresponding process number (Process ID), and then use this PID as a parameter to run the 'kill' command, so that you can end the 'rob' program. In addition to using:
pidof rob
567
kill 567
You can also try:
kill `pidof rob`
How about it, has the efficiency improved?
In the next article, I will introduce two other practical mechanisms of shell: file name matching and output redirection.
Article 4: File name matching/output redirection
1. File name matching
File name matching allows you to specify multiple files without having to write out the names one by one. You will use some special characters, called wildcards.
Suppose you want to use the 'rm' command to delete all files ending with the string '.bak' in the directory. In addition to following 'rm' with all file names as arguments, you can also use the wildcard '*':
rm *.bak
'*' can match one or more characters. In this example, you tell the shell to extend the parameters of the command 'rm' to "all files ending with '*.bak'", and the shell tells the extended parameters of the shell to tell the 'rm' command.
You will see that the shell will read and interpret the command line before the command is executed. It is because of this that you can use wildcards in arguments to shell commands.
Let's go further to understand the wildcard '*'. Suppose you have a directory containing files '', '' and ''. You want to keep only the files '', you can use:
rm *4*.bak
The shell expands '*4*.bak' into "all strings with '4' and ends with '.bak'".
Note that rm 4*.bak does not work because this matches files starting with '4'. Since there is no such file in the directory, the shell expands this pattern to an empty string, so 'rm' will return an error message:
rm: cannot remove `4*.bak': No such file or directory
If you want to keep the file '', while deleting '' and ''. This seems a bit difficult because the name of the deleted file is different except for the suffix. But luckily, you can specify the file with no:
rm *[!6].bak
This will be read as: except for files ending with '', delete all other files ending with '.bak'. You must put the negation sign and the inverse character (here is 6) in brackets, otherwise the shell will interpret the exclamation mark as the beginning of a history substitution. Taking the inverse is valid in all matching patterns introduced in this article.
Please note: the wildcard '*' is used in conjunction with the inverse sign, which can easily cause problems. Guess
rm *[!6]*.bak
What does it mean? This command will delete all files, even files with '6' in their name. If you put the wildcard '*' before and after the inverse, actually taking the inverse will fail because the shell interprets it as "a file that does not contain that character anywhere in all names". In our case, only the files'' do not conform to this pattern.
The second wildcard is the question mark: '?'. When matching, a question mark can only represent one character. To demonstrate its purpose, we add two new files to the assumption in the above example: '~' and ''. Now list all files with four characters after the dot:
ls *.????
The question mark wildcard can effectively avoid the above-mentioned "negation trap" (negation trap):
rm *[!4]?.*
It will be expanded to "all files except the penultimate character before the dot is '4'", that is, only files are retained ''.
You might ask, are there any other ways to match? So far you have only seen ways to match unique characters at the specified location. But you can do this too:
ls [13]*
All files starting with the characters '1' or '3' will be listed; in our case, the files '', '~' and '' match. Note that you have to enclose the matching patterns in brackets, otherwise the patterns only match files starting with the string '13'.
Next, you will be happy to see that you can also define the range of matches:
ls *[3-8]?.*
The file that lists all the penultimate characters before all dots fall into the range '3' to '8'. In our example, the matching files are '' and ''.
2. Special characters that quote shell
However, the above mechanisms have one disadvantage: the shell always tries to expand before the command is executed. Sometimes, it can get tricky:
l The file name contains special characters. Suppose you have a file named '!' in that directory. The following is an attempt to match the pattern:
rm !*
rm
rm: too few arguments
The shell interprets '!*' as a replacement for history (adding all parameters of the previous command), rather than a matching method.
l The command itself takes special characters as parameters. Some command-line tools under Linux, such as (e)grep, sed, awk, find and locate, use their own regular expressions. These expressions look surprisingly similar to pattern matching, but differ in some places.
But in order for these special commands to take effect, the shell cannot first explain them as pattern matching:
find . -name [1-9]* -print
find: paths must precede expression
It should be:
find . -name '[1-9]*' -print
./
./
./
./~
You can refer to special characters through backslash, such as ! , $ , ? or space:
ls \!*
!
Or use (single) quotes:
ls '!'*
!
Please note that you should see clearly where the quotes should be placed. The command ls '!*' will look for a file named '!*', because the wildcard is also in quotes, so it can only be explained literally.
3. Output redirection
The philosophy of Unix is to bring together many applets, each with special expertise. Complex tasks are not completed by large software, but are completed by using shell mechanisms and combining many mini programs. Redirection plays an important role in this.
1. Redirect between multiple commands
This is determined by pipes, and is marked by pipe symbols. The syntax is:
command1 | command2 | command3 etc.
You must have seen this format. Pipelines often send the output of a program to 'more' or 'less' to read.
ls -l | less
Among them, the first command provides the directory contents, and the second displays it as a page turn. More complex examples such as:
rpm -qa | grep ^x | less
The first command gives all installed RPM packages, the second filters them (filter: 'grep'), leaving only packages starting with '^x', and the third command displays the results as page-turning.
2. Redirect to file
Sometimes, you want to save the output of the command to a file, or take the contents of the file as an argument to the command. This can be achieved through '>' and '<'.
command > file
Save the output of command to file, which overwrites the contents in the file:
ls > dirlist
Save the contents of the current directory to the 'dirlist' file.
command < file
Take the file content as input to command:
sort < dirlist > sdirlist
Send the contents of the file 'dirlist' to the command 'sort', and then send the sorted results to the file 'sdirlist'. Of course, you can also get it in one step:
ls | sort > sdirlist
A special way is 'command 2> file'. This sends the command execution error message to the file. You will need this at that time...
Another type of operator is '>>', which adds the output to an existing file:
echo "string" >> file
Add string to file. This is a good way to complete editing without opening the file!
However, both the '<' and '>' operators have an important limitation:
command < file1 > file1
The content of file1 will be deleted, and
command < file1 >> file1
But it works well, adding the processed file1 content back to the file.
Isn't it a little too much? ;-) Don’t panic, you can learn step by step at your own speed. Don't forget that practice is the best way to learn...
After knowing the mechanisms of many shells, you may be anxious to know how to customize your environment. In the next two articles, you will get inspiration in this regard. In the last article, there is also a FAQ on how to handle shell error messages and some configuration tips.
Article 5: bash configuration file/prompt/change $PATH
1. bash configuration file
In your home directory, run
ls .bash*
You will see these files:
l.bash_history: records the command you entered before,
l.bash_logout: The command to be executed when you exit the shell,
l.bash_profile: The command to execute when you log in to the shell,
l.bashrc: The command to be executed every time a new shell is opened.
Note the difference between the latter two: '.bash_profile' is read only once at the beginning of the session, while '.bashrc' is read every time a new terminal (such as a new xterm window) is opened. By tradition, you have to put defined variables, such as PATH, into '.bash_profile', and like aliases (alias) and functions, in '.bashrc'. But since '.bash_profile' is often set to read the content of '.bashrc' first, if you want to save trouble, put all configurations into '.bashrc'.
These files are the settings for each user. System-level settings are stored in files under '/etc/profile', '/etc/bashrc' and directory '/etc/'. But you have to get used to using their own configuration files: editing does not require 'root' permission, and it can also make your settings more personalized. When the system level conflicts with the user level settings, the user's settings will be adopted.
Read the content of '.bashrc', if you want to save some trouble, put all your configuration into '.bashrc'.
The above files are the settings of each user, and the system-level settings are stored in files under '/etc/profile', '/etc/bashrc' and directory '/etc/'. You'd better get used to using your own configuration files: editing does not require 'root' permission, and it can also make your settings more personal. When there is a conflict between the system level and the user level settings, the user's settings will be preferred.
2. Prompt
Every time you open a console or xterm, the first thing you see is the prompt (prompt), similar to:
account@hostname ~ $
By default, the prompt will display your username, hostname (default is 'localhost'), and the current directory (in Unix, '~' means your home directory).
By tradition, the last character can identify whether you are a normal user ($), or 'root' (#).
You can set the prompt via the $PS1 variable. Order
echo $PS1
The current settings will be displayed. The meaning of the available characters is explained in the 'PROMPTING' section of man bash.
How can I complete the ideal setup? For forgetful beginners, the default setting is a bit unfriendly, because the prompt only displays the last part of the current directory. If you see a prompt like this
tom@localhost bin $
Your current directory may be '/bin', '/usr/bin', '/usr/local/bin' and '/usr/X11R6/bin'. Of course, you can use
pwd (output the current directory, print working directory)
Can you call the shell to automatically tell you the current directory?
sure. The settings I will mention here, including the prompt, are mostly included in the file '/etc/bashrc'. You can change the settings by editing '.bash_profile' and '.bashrc' in their respective home directories.
In the 'PROMPTING' section in man bash, these parameters are explained in detail. You can add some gadgets such as the current time in different formats, the history number of the command, and even different colors.
In '~/.bashrc', my favorite settings are:
PS1="\[\033[1m\][\w]\[\033[0m\] "
The setting of 'root' in '~/.bashrc' is:
PS1="\[\033[0;31m\][\w]\[\033[0m\] "
This way the prompt I get is:
[/usr/bin]
When using 'root', it becomes:
[/usr/bin]
I've removed the hostname and username because I don't need that. But first of all, I can tell whether my identity is an ordinary user or a 'root' at a glance. Note that the prompt for ordinary users can be in black and white characters, or in white characters.
To get the appropriate color configuration on the terminal, you can edit the following script color, give execution permissions (chmod +x color), and then run it.
#!/bin/bash
#
# This file echoes a bunch of color codes to the
# terminal to demonstrate what's available. Each
# line is the color code of one forground color,
# out of 17 (default + 16 escapes), followed by a
# test use of that color on all nine background
# colors (default + 8 escapes).
#
T='gYw' # The test text
echo -e "\n 40m 41m 42m 43m\
44m 45m 46m 47m";
for FGs in ' m' ' 1m' ' 30m' '1;30m' ' 31m' '1;31m' ' 32m' \
'1;32m' ' 33m' '1;33m' ' 34m' '1;34m' ' 35m' '1;35m' \
' 36m' '1;36m' ' 37m' '1;37m';
do FG=${FGs// /}
echo -en " $FGs \033[$FG $T "
for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
do echo -en "$EINS \033[$FG\033[$BG $T \033[0m";
done
echo;
done
echo
A more appropriate setting:
PS1="\u: \w\\$ "
In this way, the prompt becomes:
user_name: /usr/bin$
You can test different settings by using the command export (for example, export PS1="\u: \w\\$ "). If you find a suitable prompt, put the settings into your '.bashrc''. This will take effect every time the console or terminal window is opened.
You can even set the theme to the prompt, i.e. match it with different colors to make it look like a great one.
C64 prompt. If you are interested in this, you can take a look
Bashish( /arnognulf/ )。
3. Change $PATH
'$PATH' is the same as '$PS1', and is an environment variable. enter
set
All currently defined environment variables will be listed.
The environment variables you see are defined in the shell's configuration file, which may be the user's own configuration file, or may be defined by 'root' through the system-level file below '/etc'. If you use X, some more variables will be configured by X, your window manager, or the startup file of your desktop environment.
If you are not very clear about these settings, it is best not to change them casually for the time being. It is useful to know how to change the $PATH variable because this variable determines which directories the shell will look for commands or programs. If the directory of the command to be executed is in $PATH, you don't have to enter the full path of this command, just enter the command. Some third-party software does not place executable files into the standard Linux directory. Therefore, adding these non-standard installation directories to $PATH is a solution. Additionally, you will see how to deal with general environment variables.
First, as a convention, all environment variable names are capitalized. Since Linux is case sensitive, you should be careful about this. Of course, you can define some variables yourself, such as '$path', '$pAtH', but the shell ignores them.
The second point is that variable names sometimes start with '$', but sometimes they are not. When setting a variable, you use the name directly without adding '$':
PATH=/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin
To get the value of a variable, you must add '$' before the variable name:
echo $PATH
/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin
Otherwise, the variable name will be treated as normal text:
echo PATH
PATH
The third thing to note when dealing with $PATH variables is that you cannot just replace the variables, but add the new string to the original value. In most cases you can't use 'PATH=/some/directory' because this will remove all other directories in $PATH so that you have to give the full path when you run the program in that terminal. Therefore, only add:
PATH=$PATH:/some/directory
In this way, PATH is set to the current value (denoted by $PATH) + the newly added directory.
So far, you have only set a new $PATH variable for the current terminal. If you open a new terminal and run echo $PATH , the old $PATH value will be returned without seeing the new directory you just added. Because you previously defined a local environment variable (only to the current terminal).
To define a global variable to take effect in a later opened terminal, you need to output the local variable (export), you can use the 'export' command:
export PATH=$PATH:/some/directory
Now if you open a new terminal, enter echo $PATH and you can see the newly set $PATH. Please note that the command 'export' can only change the variables in the current terminal and the terminals running later. No effect on the terminal that is already running.
To permanently add the directory to your $PATH , just add that line of 'export' to your '.bash_profile' file.
Please do not set PATH in '.bashrc', otherwise it will cause unexpected growth of directories in PATH. Every time you open a new shell, '.bashrc' will work. So if you add a directory to the file, each time you open a terminal, the directory will be added again. This will cause the PATH variable to continue to grow due to directory copying.
Article 6: Command alias, Shell functions/From here/Shell FAQ
1. Command alias, shell functions
Remember all the commands and the options they come with, and then type them one by one at a time, which is really a bit boring. But luckily, you can define shortcuts for common commands. These shortcuts can be defined with simpler command alias or more complex shell functions syntax.
1. Alias for commands
For example, I use the following command to upload a file in MUO:
rsync -e ssh -z -t -r -vv --progress /home/tom/web/muo/rsmuo/docs muo:/www/mandrakeuser/docs
Obviously, if I had to enter one by one every time, I would sooner or later turn into wood. So I defined the alias in '~/.bashrc':
alias upmuo='rsync -e ssh -z -t -r -vv --progress /home/tom/web/muo/rsmuo/docs muo:/www/mandrakeuser/docs'
Now, I just need to type upmuo to complete the upload task.
The syntax for defining an alias is:
alias shortcut='command'
If there are spaces in the command, you need to use quotes (such as spaces between the command and the optional). Note that you can use single or double quotes, but they are different.
Single quotes will strip all characters from the special meaning, while '$' (parameter replacement) and '`' (command replacement) in double quotes are exceptions. This means that if you want to apply a replacement of variables or commands in an alias, you have to use double quotes. Looking at the example above, I defined a variable called MUOHOME in '.bashrc':
export MUOHOME=$HOME/web/muo/rsmuo/docs
To use this variable in the alias above, I have to use double quotes:
alias upmuo="rsync -e ssh -z -t -r -vv --progress $MUOHOME muo:/www/mandrakeuser/docs"
Otherwise, the alias will look for a directory or file named '$MUOHOME'.
You can use 'alias' to quickly create alias on the command line, or put the commands in their respective '~/.bashrc', or put them in the system-level '/etc//' (and in Mandrake Linux 8 before, '/etc/bashrc' was used). To delete an alias, just type: unalias alias . Running alias will list all the alias defined in your system.
If you look at '~/.bashrc' and '/etc//', you will find that the system has some alias defined. You can define multiple aliases for the same command. Of course, you have to confirm that the alias is different from other program names, such as alias rm='ls -l', which does not work. You can enter these shortcuts on the command line and test it out. If the shell cannot find a command with the same name, you can use it as an alias.
The following alias may be useful (don't forget the quotes!):
l alias rpmq='rpm -qa | grep' : Now rpmq string will list all installed RPM packages with string in their names,
l alias ls='ls -ho --color | more' : ls will list files in color paging, the file size is in KB.
l alias use='du --max-depth=1 | sort -n | more' :use Arrange subdirectories by size and list them in pagination.
The alias of the directory can also be removable media: alias dlm='/mnt/cdrom/RedHat/RPMS/' .
Tip: Aliases with similar functions will start with the same letter, such as starting with 'd' for all directories, which will help memorize.
I believe you will use these features.
2. Shell function
Writing shell functions involves shell scripts, which is beyond the scope of our discussion (not within my grasp ;-)). In fact, shell functions belong to shell scripts, but can be preloaded and executed under the same shell (while a general shell script must open at least one sub-shell).
With shell functions, you can do a lot of things that aliases cannot do. Here is an example:
function apros() { apropos $1 | egrep -v '(3|\(n\)'; }
A new command is defined, called 'apros'. apros name will first execute 'apropos name' (i.e. search for the command in the man page), then send the obtained output to the pipeline (|), then filter with 'egrep' to exclude the man page in chapters '3' and 'n'. This command may not be of great use, but you can organize the output of the 'apropos' command.
Functions allow you to use runtime parameters anywhere inside the function. As for the alias, only one parameter is allowed at the end of the command line (such as the previous alias 'rpmq').
'$1' is the positional parameter, which represents the position identifier of the first parameter of the function. And so on, there are '$2' and so on.
function apros() { apropos $1 | egrep -v "\($2"; }
If you run the 'apros' command like this:
apros name man_section_number
This command will search for man pages with name in the title, but exclude the man_section_number section:
apros menu 3
Search for man page with the title 'menu', but excludes chapter 3 (about programming). Notice that you have to quote twice, and you also use double quotes:
l You must refer to the search pattern of 'egrep' so that it will not be misunderstood by the shell.
l You must use double quotes so that the second parameter can be interpreted correctly.
l You must refer to parentheses so that 'egrep' treats the parameters literally.
Isn't it interesting? ;-)
The shell function handles similarly to aliases: put it in your '.bashrc' file so it will take effect permanently.
2. Start from here
All we are talking about is the beginning of the shell. With the shell script mastered, you can do many things, such as automating tasks, correcting errors in other people's scripts, and customizing Linux systems as you are used to. If you are planning to learn some complex programming language, shell scripting is also a good start, because the basic concepts are similar.
BASH Programming - Introduction HOW-TO:
/mdw/HOWTO/
Will go deeper into these topics and will take you to the world of shell programming. Then you can continue reading the Advanced Bash-Scripting Guide ( /mdw/LDP/abs/html/ ) that I highly recommend, by: Mendel Cooper.
If you prefer paper books, I recommend "Teach Yourself Shell Programming" by S. Veeraraghavan, Sams Press. I think O'Reilly's company Learning the bash Shell by Newham/Rosenblatt, but I may only see this ;-).
In addition to these, it is practice, practice, and practice. Read shell scripts written by others to see what they are doing, how they do it, and why they do it that way.
Please do not test your script with 'root'. Have fun .
About this article
Brother flaboy posted it in the forum SHELL discussion area when he compiled it. It was posted as a form of SHELL basic textbook. When he compiled it, he "did the relevant chapters be deleted and modified accordingly when compiling this article, and some content targeting Mandrake Linux were removed."
I saw that this document is very good, so I sorted it out again and adjusted the structure of the document. According to the content of the document, I appropriately added the serial number and made a directory, mainly to facilitate everyone to read; I thank the original author and Chinese translator, and also thank Brother Flaboy for his organization;
It is also a happier thing for me to organize documents. At least when I read the documents, I can know what is more important and get what I want to learn, so I will always organize documents; if time allows and have the ability, I will also write some. ──North, South, North
There is no technical content in organizing documents, so why do you do it?
Although there is no technical content, I think if it can bring a little convenience to others, I think what I have done is worth it. Compared with the original creators and Chinese translators, what is what I have done?
──North, South, North