Bash Shell Programming Quick Start Tutorial

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

Shell commonly known as shell (used to distinguish from the kernel), refers to the "user interface to provide users" command parser (software). It is similar to DOS command and later cmd.exe. It receives the user command and then invokes the appropriate application.

At the same time, the shell is a programming language. As a command language, it interactively interprets and executes commands entered by the user, or automatically interprets and executes a predetermined sequence of commands. The shell does not need to be compiled to execute, unlike languages such as C + +. As a programming language, the Shell defines variables and parameters and provides a number of control structures that are available in high-level languages, including loops and branches.

There are many versions of Shell,bash on UNIX systems that are the standard configuration of various Linux distributions, and/bin/sh are often symbolic links to/bin/bash on Linux systems.

1 Simple Hello world! program

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:

#!/bin/bash # very simple Exampleecho Hello world

This is the simplest BASH program that has been written, and each of the following describes the effect of each line.

    • First line: In Bash, the first line of "#!" and subsequent "/bin/bash" indicate that the file is a bash program that needs to be interpreted by the Bash program in the/bin directory.
    • Second line: "# This 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.
    • Three lines: The Echo statement's function is to output the string after 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: There are no semicolons at the end of most statements in BASH.

There are two ways to perform a change, one is to explicitly develop BASH to execute, the following two commands:

$ bash hello$ sh Hello                 # here sh is a link to bash

Another way, you can change the hello file to execute the file and then run it directly. At this time because of the "#!/bin/bash" in the first line of the hello file, the system will automatically use the/bin/bash program to explain the execution of the hello file:

$ chmod u+x Hello          # modified to executable $./hello                  # Execution

Note: After the BASH program is executed, the Linux system is actually running another process.

2 input, output, and error outputs

In a character terminal environment, the concept of standard input/standard output is well understood:

    • Input: Refers to the input of an application or command, whether it is entered from the keyboard or from another file;
    • Output: Refers to some information generated by an application or command;
    • Error output: There is a standard error output under the Linux system concept, unlike the Windows system, the concept is mainly for program debugging and system maintenance purposes set, error output from the standard output separate, can let some advanced error information does not interfere with the normal output information, convenient for the general user's use.

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 on top). In BASH, when these concepts are used, standard output is generally represented as 1, and the standard error output is represented as 2. Here are some examples of how to use them.

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 first command redirects the result output of the LS command to the Ls_result file, the second command appends the result of the ls-l command to the Ls_result file, and two commands are not output to the screen.

    • The symbol for output redirection (both standard output and standard error output).
    • >>: The output is appended without purging the original content.

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. If you execute directly

Find/home-name lost* > All_result

The result is that only standard output is stored in the All_result file, so what if you want the standard error output to be stored in the same file as the standard input? Look at the following example:

$ find/home-name lost* > All_result 2>& 1     # or $ find/home-name lost* >& all_result          # Concise notation

In this example, the standard error output is first redirected to the standard output, and the standard output is redirected to the All_result file. This allows us to store all the output in the All_result file.

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-n Ame 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 in the/source/directory directory are moved to the/dest/directory directory quickly by compressing and decompressing. This command will show a special advantage when/source/directory and/dest/directory are not in the same file system.

Here are a few more common uses:

    • n<&-: Indicates that the n number input is closed
    • <&-: Indicates off standard input (keyboard)
    • n>&-: Indicates that the n output is turned off
    • >&-: Indicates that standard output is turned off
3 Variables

For programmers who are familiar with C, we will explain how the definition and usage in BASH differ from that of the C language. The variables in BASH cannot contain reserved words, cannot contain reserved characters such as "-", and cannot contain spaces.

3.1 Brief description

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. Let's take a look at the following example:

First Use VI to edit the following file Hello2:

#!/bin/bash# give the Initialize value to strstr= ' Hello world ' echo $STR

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

    1. When assigning a variable, ' = ' cannot have spaces on either side;
    2. A semicolon (";") is not required at the end of a statement in BASH );
    3. In addition to assigning values in variables and in the header of a For loop statement, the variables used in BASH must have a "$" symbol in front of the variable.
    4. Because the BASH program runs 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.

Even more detailed documentation mentions that a variable enclosed in single quotes 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 {}.

3.2 integers and string variables

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:

#!/bin/bashx=1999let "x = $x + 1" echo $xx = "Olympic" $xecho $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:

corresponding operation integer action string operation
same as -eq =
different -ne !=
greater than -gt >
less than -lt <
-ge &NBSP;
less than or equal to -le &NBSP;
&NBSP; -z
&NBSP; -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]

Note: Try not to use-n when comparing strings. -Z to replace. (where the symbol "!" indicates negation)

3.3 File Variables

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.

3.4 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:

#!/bin/bashhello=hellofunction Hello {    local hello=world    echo $HELLO}echo $HELLOhelloecho $HELLO

The result of the execution of the program is:


The result of this execution shows 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.

3.5 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.6 Special Operations

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 yet 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 if the variable $var has been set, returns the value of otherwise, otherwise returns null (NULL).
    • ${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:

#!/bin/bashecho ${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}: Used to strip the shortest (longest) and pattern-matching leftmost string from the variable $var.
    • ${var%pattern}, ${var%%pattern}: The rightmost string that is used to strip the shortest (longest) and pattern matches from the variable $var.
3.7 Bash variables differ from c variables

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.

    1. A variable in BASH needs to precede the variable with a "$" symbol (the first assignment and the "$" sign in the head of the For loop);
    2. There are no floating-point operations in BASH, so there are no floating-point variables available;
    3. The comparison notation for the shaping variables in BASH is completely different from the C language, and the arithmetic operations of the shaping variables need to be handled by a let or expr statement.
4 Process Control Syntax

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

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]then    STATMENTSFI


If [expression]then    statmentselse    STATMENTSFI


If [expression]then    statmentselse if [expression]then    statmentselse    STATMENTSFI


If [expression]then    statmentselif [expression]then    statmentselse    STATMENTSFI

Note: If you write if and then succinctly in one 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:

#!/bin/bashif [$1-GT 90]; Then    echo "Good, $ elif [$1-gt]then    echo" OK, "else    echo" bad, $ fiexit 0

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

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 Indo    Statmentsdone

Where $var is the loop control variable, which is a collection that $var need to traverse, the Do/done contains the loop body, which is equivalent to a pair of curly braces in the C language.

Note: 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:

#!/bin/bashfor Day in Sun Mon Tue Wed Thu Fri satdo    Echo $daydone

# 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" do    echo $daydoneexit 0

Note: In the above example, 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 a subsequent in part, Day will take all the arguments of the command line. such as this program:

#!/bin/bashfor Paramdo    echo $paramdoneexit 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.

4.3 while/until

The basic structure of the while loop is:

While [condition]do    Statmentsdone

The basic structure of the Until loop is:

Until [condition is TRUE]do   statmentsdone

These two structures also ask you to write your own examples to verify.

4.4 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    condition1) statments1;;    Condition2) statments2;;    ...    *) statments2;;   Default statments;; Esac

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

#!/bin/bashecho "hit a key and then hit return." Read Keypresscase "$Keypress" in    [A-z]) echo "lowercase letter";;    [A-z]) echo "uppercase letter";;    [0-9]) echo "Digit";;    *) echo "punctuation, whitespace, or other";; Esacexit 0

The Read statement in line Fourth of "read Keypress" in the above example indicates that input is read from the keyboard.

4.5 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.

5 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.

Note: 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.

The 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 specified at the function definition, only when the function is called, with BASH's reserved variable ... To be quoted on it. BASH can return a specific integer using the return statement, and if no return statement explicitly returns a value, the return value is the result of the last statement of the function (typically 0, if execution fails to return an error code). The function return value is in the body of the program that called the function, through $? Reserved words to get. Let's take a look at the example of using a function to calculate the square of an integer:

#!/bin/bashsquare () {Let    res = $ * $ "    return $res}square $1result=$?echo $resultexit 0

Description: Whether the processing of a BASH script return value in the Shell or the handling of a function return value in a script 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.

6 Random number

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

#!/bin/bash# Prints different random integer from 1 to 65536a= $RANDOMecho $aexit 0

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

7 operator

Arithmetic operators

    • +-*/%: Indicates subtraction and take-rest operations
    • + = = *=/=: Meaning in the same language as C

Bitwise operators

    • << <<= >> >>=: Indicates that a bit moves left and right one operation
    • & &= | |=: Indicates bitwise AND, bit, or operation
    • ~!: Indicates non-operational
    • ^ ^=: Represents XOR or Operation

Relational operators

    • < > <= >= = = = = = = Greater than, less than, greater than or equal to, less than equals, equals, not equal to operation
    • && | | : Logical And, logical, or operational
8 Designing a simple user interface

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

Select Var indo    statments use $vardone

When executed, BASH adds a numeric column to all items and waits for the user to select it on the screen. After the user has made a selection, the variable $var contains the selected string, which can then be used for the desired action. We can understand this feature more intuitively from the following example:

#!/bin/bashoptions= "Hello Quit" select opt in $OPTIONS; Do    if ["$opt" = "Quit"], then        Echo did        exit    elif ["$opt" = "Hello"]; then        echo Hello World    El Se        clear        echo bad option    Fidoneexit 0

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

9 Read user input

BASH reads the user input through the Read function, as in the following procedure:

#!/bin/bashecho Please enter your nameread nameecho "hi! $NAME! " Exit 0

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

In addition, BASH provides a structure called the here documents, which can be used to read directly from the program body, such as a password, by changing the string that the user needs to enter the keyboard. The following applet demonstrates this feature:

#!/bin/bashpasswd= "[email protected]" ftp-n localhost <<ftpftpuser anonymous $passwdbinarybyeFTPFTPexit 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 <<somespecialstringstatments ... Somespecialstring

Here, after the command that requires keyboard input, add the << symbol directly, then follow a special string, then enter all the characters that should be entered by the keyboard sequentially, and after the end, repeat the "special string" after the previous << symbol to indicate the end of the input.

101 Special methods of usage10.1 Brackets

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

10.2 Colon

: There are two meanings, one is to represent an empty statement, a bit similar to a single ";" in C, which means that the line is an empty command. If used in the head structure of the While/until, the value 0 will cause the loop to go on, as in the following example:

While:d o    operation-1    operation-2 ...    Operation-ndone

In addition, you can also use to find the values of the following variables, such as:

#!/bin/bash: ${hostname?} {USER?} {MAIL?} echo $HOSTNAMEecho $USERecho $MAILexit 0

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

BASH Program Debugging

With the Bash-x bash-script command, you can see exactly where the 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 followed by "#!/bin/bash" and is a non-commented code, for example:

Trap ' message $checkvar 1 $checkvar 2 ' EXIT

That's all that bash writes about QuickStart.

Bash Shell Programming Quick Start Tutorial

Related Article

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.