Bash under Linux

Source: Internet
Author: User
Tags arithmetic arithmetic operators bitwise bitwise operators function definition uppercase letter

Basic syntax for BASH
    • The simplest example of--hello world!

    • About input, output, and error outputs

    • Rules for variables in BASH (similarities and differences with C language)

    • Basic Process Control syntax in BASH

    • Use of functions

2.1 Simplest example of--hello world!

Almost all of the first examples of programming books to readers are 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:

# This was a very simple example
Echo Hello World

So the simplest one BASH program is written. Here are a few questions to explain:

One, the first line of #! What is the meaning
Second, what does the first line of/bin/bash mean?
Three, is the second line a comment?
Four, Echo statement
Five, how to execute the program

#! is a description of the type of hello file, which is somewhat similar to the meaning (but not the same) of different file types under Windows system with different file suffixes. The Linux system determines the type of the file according to the "#!" and the information behind the string, and the students can learn more about it after they go back to the "Man Magic" command and the/usr/share/magic file. The "#!" and the "/bin/bash" in the first line of bash indicate that the file is a bash program that needs to be interpreted by the Bash program in the/bin directory. Bash This program is generally stored in the/bin directory, if your Linux system is more special, bash may also be stored in/sbin,/usr/local/bin,/usr/bin,/usr/sbin or/usr/local/sbin such as the target If you can't find it, you can use the three commands "locate bash" "Find/-name bash 2>/dev/null" or "Whereis bash" to find out where bash is located, and if you still can't find it, you may need to install it yourself. BASH software package.

The second line of "# is a ..." is the Bash program's comment, in the bash program from the "#" sign (note: followed by "!") To the end of the line) is considered a comment of the program. The function of the three-line Echo statement is to output the string behind echo to the standard output. Because Echo is followed by the string "Hello World", the word "Hello World" is displayed on the screen of the console terminal. Note that there is no semicolon at the end of most statements in BASH.

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

$ bash Hello or
$ sh Hello (here sh is a link to bash, "lrwxrwxrwx 1 root root 4 05:41/bin/sh, bash")

Alternatively, you can change the hello file to a file that can be executed, and then run it directly, because the "#!" in the first line of the Hello file /bin/bash "function, the system will automatically use the/bin/bash program to explain the execution of the hello file:

$ chmod u+x Hello

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

It is important to note that after the BASH program is executed, the Linux system is actually running another process.

2.2 about inputs, outputs, and error outputs

In a character terminal environment, the concept of standard input/standard output is well understood. Input refers to the input to an application or command, whether it is entered from the keyboard or from another file, and the output refers to some information generated by the application or command; Unlike Windows systems, there is a standard error output concept under Linux. This concept is mainly for the purpose of program debugging and system maintenance, error output in the standard output separate can let some advanced error information does not interfere with the normal output information, so as to facilitate the use of ordinary users.

In Linux systems: standard input (stdin) defaults to keyboard input, standard output (STDOUT) defaults to screen output, and standard error output (stderr) is output to the screen by default (Std above). When using these concepts in BASH, standard output is generally represented as 1, and the standard error output is represented as 2. Here are examples of how to use them, especially standard output and standard error output.

Input, output, and standard error outputs are primarily used for I/O redirection, which means that their default settings need to be changed. Let's look at this example:

$ ls > Ls_result
$ ls-l >> Ls_result

The above two commands redirect the result output of the LS command to the Ls_result file and append to the Ls_result file, instead of outputting to the screen. ">" is the symbol for the redirection of the output (standard output and standard error output), with two consecutive ">" symbols, or ">>" indicating that the original output is not cleared. Let's look at a slightly more complicated example:

$ find/home-name lost* 2> Err_result

This command adds a "2" to the ">" Symbol, and "2>" indicates that the standard error output is redirected. Because some directories under the/home directory cannot be accessed due to permission restrictions, some standard error outputs are stored in the Err_result file. Can you imagine what the find/home-name lost* 2>>err_result command would produce?

What if the Find/home-name lost* > All_result are executed directly and the result is that only the standard output is stored in the All_result file, so that the standard error output and the standard input are stored in the file as well? Look at the following example:

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

The above example will first redirect the standard error output to the standard output, and then redirect the standard output to the All_result file. This allows us to store all the output in a file. To achieve these functions, there is a simple way to do the following:

$ find/home-name lost* >& All_result

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

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

After the students go back can also test the following several redirection methods, see what results, 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 redirect operator is "-", see the following example:

$ (cd/source/directory && tar CF-.) | (Cd/dest/directory && tar xvfp-)

This command indicates that all files under the/source/directory directory are compressed and decompressed and moved quickly to the/dest/directory directory, and this command is/source/directory and/dest/directory A special advantage is shown when you are not in the same file system.

Here are a few more common uses:

n<&-means the n input is closed
<&-means to turn off standard input (keyboard)
n>&-means the n output is turned off
>&-indicates that standard output is turned off

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

Okay, so let's get to the bottom of this, and first look at how the variables in BASH are defined and used. For programmers who are familiar with C, we will explain how the definition and usage in BASH differ from that of the C language.

2.3.1. Introduction to Variables in BASH

Let's take a look at the use of variables in bash as a whole, and then analyze the different uses of variables in bash and the C language. The variables in BASH cannot contain reserved words, cannot contain reserved characters such as "-", and cannot contain spaces. Simple variables

In BASH, variable definitions are not required, and there is no definition process like "int i". If you want to use a variable, as long as he is not defined in front, it can be used directly, of course, you use the variable's first statement should be assigned to him the initial value, if you do not assign the initial value is OK, but the variable is empty (note: Is null, not 0). Do not assign an initial value to a variable although there is no grammatical objection, it is not a good programming habit. Okay, let's take a look at the following example:

First Use VI to edit the following file Hello2:

# give the Initialize value to STR
Str= "Hello World"
Echo $STR

In the above procedure we need to pay attention to the following points:

One, when the variable is assigned value, ' = ' can not have space on both sides;
Second, the end of the statement in BASH does not require a semicolon (";") );
Third, in addition to the variable assignment and in the For Loop statement header, the variables used in BASH must be in front of the variable with "$" symbol, students can change the above program to "Echo STR" and then try to see what results. ==>output:str
Four, because the BASH program is running in a new process, the variable definitions and assignments in the program do not change the values of other processes or variables of the same name in the original Shell, and do not affect their operation.

A more granular document even mentions that a variable enclosed in quotation marks will not be interpreted by BASH as a variable, such as ' $STR ', but as a purely string. And the more standard way to refer to a variable is ${str}, $STR is just a simplification of ${str}. In complex situations where ambiguity is possible, it is best to use the notation with {}.

Since the variables in BASH do not need to be defined, there is no type to say that a variable can be defined as a string, or it can be redefined as an integer. If an integer operation is performed on the variable, he is interpreted as an integer, and if the string is manipulated, he is treated as a string. Take a look at the following example:

Let "x = $x + 1"
Echo $x
x= "Olympic" "$x
Echo $x

As for the calculation of integer variables, there are several: "+-*/%", they mean the same as literal meaning. Integer operations are generally implemented by the two instructions of let and expr, such as a variable x plus 1 can be written: let "x = $x + 1" or x='expr $x + 1'

In the comparison operation, the integer variable and the string variable are different, as described in the following table:

The corresponding operation Integer operations String manipulation
Same -eq =
Different -ne !=
Greater than -gt >
Less than -lt <
Greater than or equal to -ge
Less than or equal to -le
is empty -Z
is not empty -N

Like what:

To compare strings A and b for equality write: if [$a = $b]
To determine if string A is empty write: if [-Z $a]
Determine if integer variable A is greater than B to write: If [$a-gt $b]

More detailed document recommendations in string comparisons try not to use-N, and use! -Z to replace. (where the symbol "!" indicates negation)

In addition to manipulating integers and strings, the variables in BASH are used as file variables. Bash is the Shell of the Linux operating system, so the file of the system is necessarily an important object that bash needs to manipulate, such as if [-x/root] can be used to determine whether the/root directory can be entered by the current user. The following table lists the operators used to determine file properties in BASH:

Operator Meaning (returns TRUE if the following requirements are met)
-E File File already exists
-F File File is a normal file
-S file File size is not zero
-D File File is a directory
-R File File files can be read to the current user
-W File File files can be written to the current user
-X File File files can be executed for the current user
-G file The GID flag for file files is set
-U file The UID flag for file files is set
-O File File is owned by the current user
-G file The file's group ID is the same as the current user
File1-nt File2 File File1 newer than file2
File1-ot File2 File file1 older than file2

Note: The file and File1, file2 in the table above refer to the path of one of the files or directories. About local variables

In a BASH program, if a variable is used, the variable is valid until the end of the program. To make a variable exist in a local program block, the concept of local variables is introduced. In BASH, a local variable can be declared with the local keyword when the variable is first assigned to the initial value, as in the following example:

function Hello {
Local Hello=world

The result of the execution of the program is:


The result of this execution indicates that the value of the global variable $HELLO is not changed when the function HELLO is executed. That is, the effect of the local variable $HELLO exists only in the function block.

2.3.2. The difference between a variable in BASH and a variable in the C language

Here we are not familiar with BASH programming, but very familiar with the C language programmer to summarize the use of variables in the bash environment to pay attention to the problem.

Variables in 1,bash need to precede the variable with a "$" symbol (the first assignment and the "$" sign in the head of the For loop);
There are no floating-point operations in the 2,bash, so there are no floating-point variables available;
The comparison symbol of the shaping variables in 3,bash is completely different from the C language, and the arithmetic operations of the shaping variables need to be handled by let or expr statements;

Basic Process Control syntax in 2.4 BASH

BASH contains almost all the control structures commonly used in C, such as conditional branching, looping, and so on, as described below.

2.4.1 If...then...else

The IF statement is used for judging and branching, and its syntax rules are very similar to the if of the C language. Several of its basic structures are:

if [expression]


if [expression]


if [expression]
else if [expression]


if [expression]
elif [Expression]

It is worth noting that if you write if and then succinctly in a line, you must precede then with a semicolon, such as: if [expression]; Then .... The following example shows how to use the IF condition to judge a statement:


If [$1-GT 90]
echo "Good, $ $"
elif [$1-GT 70]
echo "OK, $ $"
echo "Bad, $ $"

Exit 0

The above example refers to the first parameter of the command line, which is explained in the following "special reserved words in BASH".

2.4.2 for

The For loop structure differs from the C language in that the basic structure of the For loop in BASH is:

For $var in


Where $var is the loop control variable,

is a collection that $var need to traverse, Do/done contains the loop body, which is equivalent to a pair of curly braces in the C language. In addition, if do and for are written on the same line, you must precede do with ";". such as: for $var in; Do. Here is an example of using a For loop:


For day in Sun Mon Tue Wed Thu Fri Sat
Echo $day

# If the list is contained in a pair of double quotes, it is considered an element
For day in "Sun Mon Tue Wed Thu Fri Sat"
Echo $day

Exit 0

Note that in the example above, the variable day in the for row is not marked with a "$" symbol, and in the loop body, the Echo row variable $day must be prefixed with "$". In addition, if you write for day without the back in

Section, day will take all the parameters of the command line. such as this program:


for Param
Echo $param

Exit 0

The above program will list all command line parameters. The loop body of the For loop structure is included in the Do/done pair, which is the feature of the later while and until loops.

2.4.3 while

The basic structure of the while loop is:

while [condition]

This structure invites you to write an example to verify.

2.4.4 until

The basic structure of the Until loop is:

Until [condition is TRUE]

This structure also invites you to write an example to verify.

2.4.5 case

The case structure in BASH is similar to the function of a switch statement in C, and can be used for multiple branch control. Its basic structure is:

Case ' $var ' in
* )
Default statments;;

The following procedure is an example of a branch execution using the case structure:


echo "hit a key and then hit return."
Read Keypress

Case ' $Keypress ' in
[A-z]) echo "lowercase letter";;
[A-z]) echo "uppercase letter";;
[0-9]) echo "Digit";;
*) echo "punctuation, whitespace, or other";;

Exit 0

The Read statement in line Fourth of "read Keypress" in the above example indicates that input is read from the keyboard. This command will be explained in the other advanced questions of BASH in this handout.

2.4.6 Break/continue

Familiar with C programming is familiar with break statements and continue statements. BASH also has these two statements, and the function and usage are the same as in the C language, the break statement can let the program flow out of the current loop, and the continue statement can skip the remainder of the loop and go directly to the next loop.

2.5 Use of functions

Bash is a relatively simple scripting language, but in order to facilitate a structured design, bash also provides function-defined functionality. The function definition in BASH is simple, as long as you write to the following:

function My_funcname {
code block


My_funcname () {
code block

The second notation above is closer to the wording of the C language. The definition of a function in BASH must be defined before the function is used, which is different from the C language using the header file to describe the function method.

A further question is how to pass parameters to the function and get the return value. The definition of a function parameter in bash does not need to be made at the function definition, but only when the function is called with BASH's reserved variable ... The return value of the BASH can be specified with a return statement that returns a specific integer, and the return value is the result of the last statement of the function (typically 0 if execution fails and returns an error code) If no return statement is explicitly returned. The return value of the function is passed through $ in the program body that called the function. Reserved words to get. Let's look at an example of using a function to calculate the square of an integer:


Square () {
Let "res = $ * $"
Return $res

Square $
Echo $result

Exit 0

Special reserved words in BASH
    • Reserved variables

    • Random number

    • Operator

    • Special Operations for variables

3.1 Reserved variables

There are some reserved variables in BASH, some of which are listed below:

$IFS This variable holds the split character used to split the input parameter, and implicitly recognizes the space.
$HOME This variable stores the current user's root directory path.
$PATH This variable stores the default path string for the current Shell.
$PS 1 indicates the first system prompt.
The two system prompt represented by $PS 2.
$PWD represents the current working path.
$EDITOR represents the default editor name for the system.
$BASH represents the path string for the current Shell.
$, $, $, ...
Represents the No. 0, first, second, etc. parameters that the system passes to a script or script to a function.
$# indicates the number of command arguments or the number of arguments for a function.
$$ represents the process number of the script, which is commonly used to generate temporary files with unique file names.
$? Represents the return status value of a script program or function, normal 0, otherwise nonzero error number.
$* represents all of the script parameters or function parameters.
[email protected] and $* have similar meanings, but are safer than $*.
$! Represents the process number of the most recent process running in the background.

3.2 Random Number

Random numbers are often used, and BASH also provides this feature, see this program:


# Prints different random integer from 1 to 65536

Echo $a

Exit 0

This program can randomly print an integer size between 1 and 65536 at each execution.

3.3 operator

Arithmetic operators
+-*/% indicates subtraction and take-rest operations
+ = = *=/= with C language meaning

Bitwise operators
<< <<= >> >>= means move one operation left and right
& &= | |= indicates bitwise AND, bit, or operation
~ ! Represents a non-operational
^ ^= represents XOR or manipulation

Relational operators
< > <= >= = = = = Greater than, less than, greater than or equal, less than equals, equals, not equal to operation
&& | | Logical AND logical OR operational

3.4 Special Operations for variables

There are also some simple, fast actions for variables in BASH, and remember that "${var}" and "$var" are also references to variables, and some changes to ${var} can create new features:
${var-default} indicates that if the variable $var has not been set, the $var is not set and returns the default value that follows.
${var=default} indicates that if the variable $var has not been set, then the default value of the following is taken.
${var+otherwise} indicates that if the variable $var has been set, the value of otherwise is returned, otherwise empty (NULL) is returned.
${VAR?ERR_MSG} indicates that if the variable $var has been set, the value of the variable is returned, or the subsequent err_msg is output to the standard error output.

Ask the students to try the following examples themselves:


Echo ${var? There is an error}

Exit 0

There are several uses that are used primarily to extract useful information from a file path string:
${var#pattern}, ${var# #pattern} is used to peel the shortest (longest) and the leftmost string matching the pattern from the variable $var.
${var%pattern}, ${var%%pattern} is used to strip the shortest (longest) and the rightmost string matching the pattern from the variable $var.

In addition BASH 2 also adds some of the following actions:
${var:pos} indicates that the variable $var before the POS characters are removed.
${var:pos:len} represents the first Len character of the remaining string after the first POS character is removed from the variable $var.
${var/pattern/replacement} indicates that the first occurrence of the pattern pattern in the variable $var is replaced with a replacement string.
${var//pattern/replacement} indicates that all pattern patterns appearing in the variable $var are replaced with replacment strings.

Other advanced issues in BASH
    • Handling of return values in BASH

    • Design a simple user interface with BASH

    • Read user input in BASH

    • Some special methods of usage

    • Debugging of BASH Programs

    • About BASH2

Handling of return values in 4.1 BASH

Whether you are handling the return value of a BASH script in the Shell or handling the return value of a function in a script, it is obtained through the "$?" System variable. BASH requires the return value to be an integer and cannot return a string variable with a return statement.

4.2 Designing a simple user interface with BASH

BASH provides a small statement format that allows the program to quickly design a menu of user interaction choices for a character interface that is implemented by the SELECT statement, with the syntax of the SELECT statement:

Select Var in

statments Use $var

Once the syntax structure is executed, BASH will

All the items in the plus Number column are on the screen waiting for the user to choose, after the user makes a selection, the variable $var contains the selected string, then you can do the required action on the variable. We can understand this feature more intuitively from the following example:


options= "Hello Quit"
Select opt in $OPTIONS; Do
If ["$opt" = "Quit"]; Then
Echo Done
elif ["$opt" = "Hello"]; Then
Echo Hello World
echo Bad option

Exit 0

You can try to execute the above procedure to see what the results are.

4.3 read user input in BASH

The read function is implemented in BASH to enable reading of user input, as in the following procedure:


echo Please enter your name
echo "hi! $NAME! "

Exit 0

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

In addition, BASH also provides a structure???? called here documents, which allows you to change the string that the user needs to input through the keyboard to read directly from the program body, such as a password. The following applet demonstrates this feature:


passwd= "[Email protected]"
Ftp-n localhost <<ftpftp
User Anonymous $passwd

Exit 0

This program simulates keyboard input by using actions inside the program when the user needs to type some characters through the keyboard. Please note that the basic structure of here documents is:

Command <<somespecialstring

This requires the keyboard input after the command, directly add the << symbol, and then followed by a special string, after the string in order to enter all the characters that should be entered by the keyboard, after all the words need to be entered nonalphanumeric end, repeat the previous << symbol "special string" That means that the input ends here.

4.4 Some special methods of usage

In BASH () a pair of parentheses are generally used to find the value of an expression in parentheses or the execution result of a command, such as: (A=hello; echo $a), which acts as ' ... '.

: There are two meanings, one is to represent an empty statement, a bit similar to a single ";" in the C language. Indicates that the row is an empty command, and if used in the header structure of While/until, the value 0 will cause the loop to go on, as in the following example:


In addition: can also be used to find the value of the following variables, such as:


: ${hostname?} {USER?} {MAIL?}
Echo $USER
Echo $MAIL

Exit 0

In BASH, the Export command is used to output system variables to the outer shell.

Debugging of the 4.5 BASH program

With the Bash-x bash-script command, you can see where an error bash script is wrong and help the programmer find the error in the script.

In addition, the trap statement can be used to print out the values of some variables for the programmer to check when the BASH script exits with an error. The trap statement must be the first non-commented code following "#!/bin/bash", and the General Trap command is written: Trap ' message $checkvar 1 $checkvar 2 ' EXIT.

4.6 About BASH2

Use the bash-version command to see what version of Bash you are currently using, with a general version number of 1.14 or another version. A BASH with a version number of 2.0 is now generally installed on the machine. The BASH is also under the/bin directory. BASH2 provides a number of new features, interested in the same can see the relevant information, or direct man bash2.

Bash under Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.