Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the syntax and tools of Bash?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article shows you what the syntax and tools of Bash are, which are concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Shell is the command interpreter of the operating system, of which Bash is my favorite. Whenever a user or system administrator enters commands into the system, Linux's shell interpreter converts the commands into a form that the operating system can understand. After the execution results are returned to the shell program, it will output the results to STDOUT (standard output). By default, these results will be displayed on your terminal. All the shell I am familiar with is also a programming language.

Bash is a powerful shell with many convenient features, such as tab completion, command backtracking and re-editing, aliases, etc. Its command-line default editing mode is Emacs, but one of my favorite Bash features is that I can change it to Vi mode to use the editing commands stored in my muscle memory.

However, if you use Bash as a pure shell, you won't be able to experience its true power. When I designed a three-volume Linux self-study course (this series of articles is based on this course), I learned a lot about Bash, which I haven't learned in the past 20 years of Linux work experience, some of which is about programming usage of Bash. I have to say that Bash is a powerful programming language and a perfect design for both command line and shell scripts.

Shell

Bash is an acronym for Bourne Again Shell because Bash shell is based on the earlier Bourne shell, which was developed by Steven Bourne in 1977. There are many other shell that can be used, but here are four I often see:

Csh:C shell is suitable for developers who are used to C language syntax.

Ksh:Korn shell, developed by David Korn, is more popular among Unix users.

Tcsh: a variant of csh that adds some ease of use.

Zsh:Z shell, which integrates many other popular shell features.

All shell have built-in commands to supplement or replace the core toolset. Open the man description page of shell and find the "BUILT-INS" section to see what built-in commands are available.

Each shell has its own features and grammar style. I've used csh, ksh, and zsh, but I still prefer Bash. You can try a few more to find a shell that suits you better, although it may take some effort. Fortunately, switching between different shell is easy.

All of these shell are both programming languages and command interpreters. Let's take a quick look at the programming structures and tools integrated in Bash.

Bash as a programming language

In most scenarios, system administrators use Bash to send simple and straightforward commands. But Bash can not only enter a single command, many system administrators can write simple command-line programs to perform a series of tasks, these programs can be used as general tools, can save time and effort.

The purpose of writing CLI programs is to improve efficiency (to be a "lazy" system administrator). In the CLI program, you can list several commands in a specific order and execute them one by one. In this way, you don't have to stare at the screen, wait for one command to be executed, and then type another, and you can save time to do something else.

What is a "program"?

The Free online computer Dictionary (FOLDOC) defines programs as "instructions executed by a computer, not the physical hardware on which they are run." Princeton University's WordNet defines a program as "... a series of instructions that a computer can understand and execute." There is also a good entry on Wikipedia about computer programs.

To sum up, the program consists of one or more instructions to complete a specific related task. For system administrators, a program usually consists of a series of shell commands. All shell under Linux (at least as far as I'm familiar) have basic programming capabilities, and Bash, as the default shell for most linux distributions, is no exception.

This series uses Bash as an example (because it's ubiquitous), and it doesn't matter if you use a different shell, although the structure and syntax are different, but the programming ideas are the same. Some shell supports certain features while other shell does not, but they all provide programming capabilities. Shell programs can be used repeatedly in a file, or they can be created only when needed.

Simple CLI program

The simplest command-line program has only one or two statements that may or may not be relevant and entered into the command line before pressing enter. The second statement in the program, if any, may depend on the operation of the first statement, but it is not necessary.

A punctuation mark needs to be explained here. When you type a command on the command line and press enter, there is actually an implicit semicolon (;) at the end of the command. When a CLI shell program is strung together on the command line as a single-line instruction, you must use a semicolon to terminate each statement and separate it from the next statement. However, the last statement in a CLI shell program can use an explicit or implicit semicolon.

Some basic grammar

The following example illustrates this grammatical rule. This program consists of a single command with an explicit Terminator:

[student@studentvm1] $echo "Hello world."; Hello world.

It doesn't look like a program, but it is the first program I write when I learn every new programming language. Different languages may have different grammars, but the output is the same.

Let's extend this trivial but ubiquitous piece of code. Your results may be different from mine, because my home directory is a little messy, and you may be logging in to your account for the first time on your GUI desktop.

[student@studentvm1 ~] $echo "My home directory."; ls; My home directory.chapter25 TestFile1.Linux dmesg2.txt Downloads newfile.txt softlink1 testdir6chapter26 TestFile1.mac dmesg3.txt file005 Pictures Templates testdirTestFile1 Desktop dmesg.txt link3 Public testdir VideosTestFile1.dos dmesg1.txt Documents Music random.txt testdir1

Is it more obvious now. The result is relevant, but the two statements are independent of each other. You may have noticed that I like to enter an extra space before and after the semicolon, which makes the code more readable. Let's run the program again, this time without the semicolon at the end:

[student@studentvm1 ~] $echo "My home directory."; ls

There is no difference in the output.

About variables

Like all other programming languages, Bash supports variables. A variable is a symbolic name that points to a location in memory where the corresponding value is stored. The value of a variable can be changed, so it is called "variable".

Unlike languages such as C, Bash requires mandatory variable types, such as integers, floats, or characters. In Bash, all variables are strings. Integer variables can be used for integer operations, which is the only mathematical type that Bash can handle. More complex operations require commands such as bc, which can be used in command-line programming or scripting.

The values of variables are pre-assigned and can be used in command-line programming or scripting. You can assign a value to a variable by its name, but you cannot start with the $character. For example, VAR=10 sets the value of VAR to 10. To print the value of a variable, you can use the statement echo $VAR. The variable name must start with text (that is, not a number).

Bash saves the defined variables until they are canceled.

In the following example, the value of a variable is null before it is assigned. Then assign a value to it and print it out to check it out. You can do it in the same line of CLI program:

[student@studentvm1 ~] $echo $MyVar; MyVar= "Hello World"; echo $MyVar; Hello World [student@studentvm1 ~] $

Note: the syntax for variable assignment is so strict that there can be no spaces on both sides of the equal sign (=).

That blank line indicates that the initial value of MyVar is empty. Variables are assigned and changed in the same way, and this example shows the original and new values.

As mentioned earlier, Bash supports integer operations, which is helpful when you want to calculate the position of an element in an array, or do some simple arithmetic. However, this method is not suitable for scientific computing, or for scenarios that require decimal operations, such as financial statistics. There are other better tools to deal with these scenarios.

Here is a simple arithmetic problem:

[student@studentvm1 ~] $Var1= "7"; Var2= "9"; echo "Result = $(Var1*Var2)" Result = 63

There seems to be no problem, but what happens if the result is a floating-point number?

[student@studentvm1] $Var1= "7"; Var2= "9"; echo "Result = $((Var1/Var2))" Result = 0 [student@studentvm1 ~] $Var1= "7"; Var2= "9"; echo "Result = $((Var2/Var1))" Result = 1 [student@studentvm1 ~] $

The result will be rounded. Note that the operation is included in the echo statement, but the calculation is completed before the end of the echo command, because of the internal priority of Bash. For more information, you can search for "precedence" in Bash's man page.

Control operator

Shell's control operator is a syntax operator that makes it easy to create some interesting command-line programs. Stringing several commands together sequentially on the command line becomes the simplest CLI program:

Command1; command2; command3; command4;. . . ; etc.

As long as there are no mistakes, these commands can be carried out smoothly. But what if something goes wrong? You can presuppose ways to deal with errors by using Bash's built-in control operators & & and | |. These two operators provide flow control capabilities that allow you to change the order in which the code is executed. The semicolon can also be seen as a Bash operator that heralds the beginning of a new line.

The & & operator provides the following simple logic, "if the command1 execution succeeds, then the command2 is executed. If the command1 fails, skip the command2." The syntax is as follows:

Command1 & & command2

Now, let's use the command to create a new directory and, if successful, change it to the current directory. Make sure your home directory (~) is the current directory. Try to create it in the / root directory first. You should not have permission:

[student@studentvm1 ~] $Dir=/root/testdir; mkdir $Dir/ & & cd $Dirmkdir: cannot create directory'/ root/testdir/': Permission denied [student@studentvm1 ~] $

The above error message was thrown by the mkdir command because the creation of the directory failed. The & & operator received a non-zero return code, so the cd command was skipped, which prevented the latter from running because the creation of the directory failed. This control process can prevent the accumulation of later errors and avoid causing more serious problems. It's time for more complicated logic.

When the return code of a program is greater than 00:00, use the | operator to allow you to execute another program later. The simple syntax is as follows:

Command1 | | command2

Read, "if command1 fails, execute command2." The hidden logic is to skip command2 if command1 succeeds. Let's put it into practice and still create a new directory:

[student@studentvm1 ~] $Dir=/root/testdir; mkdir $Dir | | echo "$Dir was not created." mkdir: cannot create directory'/ root/testdir': Permission denied/root/testdir was not created. [student@studentvm1 ~] $

As expected, the first command failed because the directory could not be created, and the second command was executed.

Combine the & & and | | operators to make the most of them. Take a look at the process control method in the following example:

Pre-commands; command1 & & command2 | | command3; follow commands

Syntax explanation: "if the return code is zero when command1 exits, execute command2, otherwise execute command3." Try it with specific code:

[student@studentvm1 ~] $Dir=/root/testdir; mkdir $Dir & & cd $Dir | | echo "$Dir was not created." mkdir: cannot create directory'/ root/testdir': Permission denied/root/testdir was not created. [student@studentvm1 ~] $

Now let's try again, replace the / root directory with your home directory, and you will have permission to create this directory:

[student@studentvm1 ~] $Dir=~/testdir; mkdir $Dir & & cd $Dir | | echo "$Dir was not created." [student@studentvm1 testdir] $

Control statements such as command1 & & command2 run because each command finishes sending a return code to shell indicating whether it was successful or not. By default, a return code of 0 indicates success, and any other positive value indicates failure. Some system administrators use tools that use a return code with a value of 1 to indicate a failure, but many other programs use a different number to indicate a failure.

Bash's built-in variable $? You can display the return code of the previous command, which can be easily checked in a script or on the command line. To see the return code, let's start by running a simple command, and the result of the return code is always given by the previous command.

[student@studentvm1 testdir] $ll; echo "RC = $?" total 1264drwxrwxr-x 2 student student 4096 Mar 2 08:21 chapter25drwxrwxr-x 2 student student 4096 Mar 21 15:27 chapter26-rwxr-xr-x 1 student student 92 Mar 20 15:53 TestFile1drwxrwxr-x. 2 student student 663552 Feb 21 14:12 testdirdrwxr-xr-x. 2 student student 4096 Dec 22 13:15 VideosRC = 0 [student@studentvm1 testdir] $

In this example, the return code is zero, which means that the command was executed successfully. Now test root's home directory, you should not have permission:

[student@studentvm1 testdir] $ll / root; echo "RC = $?" ls: cannot open directory'/ root': Permission deniedRC = 2 [student@studentvm1 testdir] $

The return code is 2, indicating that non-root users do not have permission to enter this directory. You can use these return codes and use the control operator to change the order in which the program is executed.

Think of Bash as a programming language, and introduce its simple syntax and basic tools from this perspective. We learned how to output data to STDOUT and how to use variables and control operators.

The above is what are the grammar and tools of Bash. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report