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

Basic syntax of Linux Bash Shell

2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

This article mainly explains "the basic Grammar of Linux Bash Shell". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the basic grammar of Linux Bash Shell.

Basic syntax of BASH

The simplest example-Hello World!

About input, output, and error output

The definition of variables in BASH (similarities and differences with C language)

Basic process Control Syntax in BASH

The use of functions

2.1the simplest example-Hello World!

The first example given to readers in almost all books on programming is the Hello World program, so let's start with this example today to learn more about BASH.

Edit a hello file with the vi editor as follows:

#! / bin/bash

# This is a very simple example

Echo Hello World

In this way, the simplest BASH program is finished. Here are a few questions that need to be explained:

One, # in the first line! What does it mean?

Second, what does the / bin/bash in the first line mean?

Three, is the second line a comment?

Fourth, echo statement

Fifth, how to execute the program

#! It describes the type of hello file, which is similar to the meaning of using different file suffixes to express different file types (but not the same) in Windows systems. The Linux system is based on "#!" And the information behind the string to determine the type of the file, students can go back to the "man magic" command and / usr/share/magic file to learn more about this. The "#!" in the first line of BASH And the following "/ bin/bash" indicates that the file is a BASH program that needs to be interpreted and executed by the bash program in the / bin directory. BASH is usually stored in the / bin directory. If your Linux system is special, bash may also be stored in a directory such as / sbin, / usr/local/bin, / usr/bin, / usr/sbin or / usr/local/sbin. If you can't find it, you can use the commands "locate bash", "find /-name bash 2 > / dev/null" or "whereis bash" to find out the location of bash. If you still can't find it, you may need to install a BASH package yourself.

"# This is a..." in the second line. Is the comment of the BASH program, in the BASH program from the "#" sign (note: it is followed by "!" Most of the parts from the beginning to the end of the line are regarded as comments for the program. The function of the three-line echo statement is to output the string after echo to standard output. Since the echo is followed by the string "Hello World", the string "Hello World" is displayed on the console terminal screen. It is important to note that most statements in BASH do not end with a semicolon.

How to execute the program? There are two ways: one is to explicitly develop a BASH to execute:

$bash hello or

$sh hello (where sh is a link to bash, "lrwxrwxrwx 1 root root 4 Aug 20 05:41 / bin/sh-> bash")

Or you can first change the hello file to an executable file, and then run it directly. Because of the "#! / bin/bash" in the first line of the hello file, the system will automatically use the / bin/bash program to interpret and execute the hello file:

$chmod upright x hello

$. / hello

There is no direct "$hello" here because the current directory is not the default directory for the current user executable, but the current directory. " Setting it as the default directory is an unsafe setting.

It should be noted that after the BASH program is executed, the Linux system actually sets up another process to run.

2.2 about input, output, and error output

In a character terminal environment, the concept of standard input / standard output is easy to understand. Input refers to the input to an application or command, whether from the keyboard or from another file, and output refers to some information generated by the application or command Different from Windows system, Linux system also has a concept of standard error output, which is mainly set for program debugging and system maintenance. the separation of error output from standard output can make some advanced error information do not interfere with normal output information, which is convenient for general users.

In Linux systems: standard input (stdin) defaults to keyboard input, standard output (stdout) defaults to screen output, and standard error output (stderr) defaults to output to the screen (the std above represents standard). When using these concepts in BASH, standard output is generally represented as 1 and standard error output as 2. Let's give an example of how to use them, especially standard output and standard error output.

Input, output, and standard error output are mainly used for the redirection of Icano, which means that their default settings need to be changed. Let's look at this example first:

$ls > ls_result

$ls-l > > ls_result

The above two commands redirect the output of the ls command to the ls_result file and append the output to the ls_result file instead of to the screen. ">" is the representative symbol of output (standard output and standard error output) redirection, two consecutive ">" symbols, that is, ">" indicates that the output is appended without clearing the original. Let's look at a slightly more complicated example:

$find / home-name lost* 2 > err_result

This command adds a "2" before the ">" symbol, and "2 >" redirects the standard error output. Since some directories under the / home directory are inaccessible due to permission restrictions, some standard error output is stored in the err_result file. Can you imagine the result of the find / home-name lost* 2 > > err_result command?

If you execute find / home-name lost* > all_result directly, the result is that only the standard output is saved in the all_result file. What if you want the standard error output to be saved to the file as well as the standard input? Look at the following example:

$find / home-name lost* > all_result 2 > & 1

In the above example, you will first redirect the standard error output to the standard output, and then redirect the standard output to the file all_result. So that we can store all the output in the file. In order to achieve the above functions, there is another easy way to write it as follows:

$find / home-name lost* > & all_result

If those error messages are not important, the following command allows you to avoid the interference of many useless error messages:

$find / home-name lost* 2 > / dev/null

When you go back, you can try the following redirection methods again to see what the result will be and why?

$find / home-name lost* > all_result 1 > & 2

$find / home-name lost* 2 > all_result 1 > & 2

$find / home-name lost* 2 > & 1 > all_result

Another very useful redirection operator is "-", as shown in the following example:

(cd / source/directory & & tar cf -. ) | (cd / dest/directory & & tar xvfp -)

This command means that all files in the / source/directory directory will be quickly moved to the / dest/directory directory by compression and decompression. This command will show a special advantage when / source/directory and / dest/directory are not on the same file system.

Here are a few unusual uses:

Standard-indicates that standard output is turned off

2.3 provisions for variables in BASH (similarities and differences with C language)

All right, let's get down to business and take a look at how variables in BASH are defined and used. For programmers familiar with the C language, we will explain how the definition and usage in BASH are different from those in C.

2.3.1. Introduction to variables in BASH

Let's first grasp the use of variables in BASH as a whole, and then analyze the differences in the use of variables between BASH and C language. Variables in BASH cannot contain reserved words, reserved characters such as "-", or spaces.

2.3.1.1 simple variable

Variable definition is not needed in BASH, and there is no definition process such as "int I". If you want to use a variable, as long as it has not been defined before, it can be used directly, of course, the first statement you use the variable should be to assign an initial value to him, if you do not assign an initial value, it is not related, but the variable is empty (note: it is NULL, not 0). Not assigning initial values to variables is not syntactically opposed, but it is not a good programming habit. Okay, let's take a look at the following example:

First edit the following file, hello2, with vi:

#! / bin/bash

# give the initialize value to STR

STR= "Hello World"

Echo $STR

In the above program, we need to pay attention to the following points:

First, when a variable is assigned, there can be no spaces on the left and right sides of'='.

Second, statements in BASH do not need a semicolon (";") at the end.

Third, except for the assignment of variables and the beginning of FOR loop statements, the use of variables in BASH must be preceded by a "$" symbol. Students can change the third line of the above program to "echo STR" and try again to see what happens. = > output: STR

Fourth, because the BASH program runs in a new process, the definition and assignment of variables in the program will not change the value of variables of the same name in other processes or the original Shell, nor will it affect their operation.

More detailed documentation even mentions that variables enclosed in quotation marks will not be interpreted as variables by BASH, such as'$STR', but as pure strings. And the more standard variable reference is ${STR}, and $STR is simply a simplification of ${STR}. In complex situations (that is, where ambiguity is possible), it is best to use the representation with {}.

Since a variable in BASH does not need to be defined, there is no type. A variable can be defined either as a string or as an integer. If an integer operation is performed on the variable, it is interpreted as an integer; if a string operation is performed on him, he is regarded as a string. Take a look at the following example:

#! / bin/bash

Xerox 1999

Let "x = $x + 1"

Echo $x

X = "olympic'" $x

Echo $x

There are several kinds of integer variable calculation: "+-* /%", which have the same meaning and literal meaning. Integer operations are generally implemented through let and expr instructions. For example, adding 1 to the variable x can be written as: let "x = $x + 1" or x = `expr $x + 1`.

Integer variables and string variables are different in comparison operations, as shown in the following table:

Corresponding operation

Integer operation

String operation

The same

-eq

=

Different

-ne

! =

Greater than

-gt

>

Less than

-lt

= indicates that the bit moves left and right by one bit.

& & = | = indicates bitwise and, bitwise or operation

~! Represents a non-operation

^ = represents an XOR operation

Relational operator

< >

= =! = means greater than, less than, greater than or equal to, less than or equal to, not equal to operation

& & | Logic and, logic or operation

3.4 Special operation of variables

There are also some concise and fast operations on variables in BASH. Remember that "${var}" and "$var" are also references to variables, and some changes to ${var} can produce some new features:

${var-default} means that if the variable $var is not set, the state of $var is not set and the later default value default is returned.

${var=default} means that if the variable $var has not been set, the default value of default is taken.

${var+otherwise} means that if the variable $var is set, it returns the value of otherwise, otherwise it returns null (null).

${var?err_msg} means that if the variable $var is set, the value of the variable is returned, otherwise the subsequent err_msg is output to the standard error output.

Please try the following example for yourself:

#! / bin/bash

Echo ${var?There is an error}

Exit 0

There are also the following uses, which are mainly used to extract useful information from a file path string:

${var#pattern}, ${var##pattern} is used to strip the shortest (longest) leftmost string that matches pattern from the variable $var.

${var%pattern}, ${var%%pattern} is used to strip the shortest (longest) rightmost string that matches pattern from the variable $var.

In addition, the following actions have been added to BASH 2:

${var:pos} means to remove the first pos character from the variable $var.

${var:pos:len} represents the first pos character of the remaining string in the variable $len after the first len character is removed.

${var/pattern/replacement} means to replace the first occurrence of the pattern pattern in the variable $var with a replacement string.

${var//pattern/replacement} means that all pattern patterns that appear in the variable $var are replaced with replacment strings.

Other advanced issues in BASH

How to deal with the return value in BASH

Designing simple user Interface with BASH

Read user input in BASH

Some special idioms

Debugging of BASH Program

About BASH2

4.1Handling of return values in BASH

Whether it is the processing of the return value of the BASH script in Shell or the return value of the function in the script, it is through the "$?" To get the system variable. BASH requires that the return value must be an integer and cannot return a string variable with a return statement.

4.2 designing a simple user interface with BASH

A small statement format is provided in BASH, which allows the program to quickly design a user-selected menu with a character interface. This function is realized by select statements. The syntax of select statements is:

Select var in

Do

Statments use $var

Done

After the above syntax structure is executed, BASH sets the

All the items in the plus numbers are listed on the screen waiting for the user to select, and after the user makes the selection, the variable $var contains the selected string, and then you can perform the desired operation on the variable. We can understand this feature more intuitively from the following example:

#! / bin/bash

OPTIONS= "Hello Quit"

Select opt in $OPTIONS; do

If ["$opt" = "Quit"]; then

Echo done

Exit

Elif ["$opt" = "Hello"]; then

Echo Hello World

Else

Clear

Echo bad option

Fi

Done

Exit 0

You can try to execute the above program and see what the implementation result is.

4.3 read user input in BASH

BASH implements the function of reading user input through the read function, such as the following program:

#! / bin/bash

Echo Please enter your name

Read NAME

Echo "Hi! $NAME!"

Exit 0

The above script reads the user's input and echoes it on the screen.

In addition, BASH also provides another structure called here documents, which can change the string that the user needs to enter through the keyboard to read directly from the program body, such as a password. The following Mini Program demonstrates this feature:

#! / bin/bash

Passwd= "aka@tsinghua"

Ftp-n localhost

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