Bash Hello world! (Zz)

Source: Internet
Author: User
The simplest example is Hello world!
Almost all the books that explain programming give readers the first example of the hello World Program, so today we will start from this example to learn more about Bash.

Edit a hello file in the VI editor as follows:

#! /Bin/bash
# This is a very simple example
Echo Hello World

In this way, the simplest bash program is compiled. Here are a few questions to explain:

1. The first line #! What does it mean?
2. What does/bin/bash in the first line mean?
3. Is the second line annotated?
Iv. Echo statement
5. How to execute the program

#! It indicates the type of the "hello" file. It is a bit similar to using different file suffixes in Windows to indicate the meaning of different file types (but not the same ). For Linux "#! "And the information following this string determine the file type, after you go back, you can use the "man Magic" command and the/usr/share/magic file to learn more about this. In bash, the first line "#! "And later"/bin/bash "indicates that the file is a bash program and must 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/sbin,/usr/local/bin,/usr/bin,/usr/sbin, or/usr/local/sbin; if not, you can use the "locate Bash" "find/-name bash 2>/dev/null" or "whereis Bash" commands to find the location of bash; if you still cannot find it, you may need to install a bash package by yourself.

In the second line, "# This is a..." is the comment of the bash program, starting from "#" in the bash Program (Note: followed by "!" (Except for the number. The function of the Three-line echo statement is to output the string following echo to the standard output. Because ECHO is followed by the "Hello World" string, the "Hello World" string is displayed on the console terminal screen. Note that most statements in bash do not end with semicolons.

How to execute this program? There are two methods: one is to explicitly execute Bash:

$ Bash hello or
$ Sh Hello (here SH is a link to bash, "lrwxrwxrwx 1 Root 4 Aug 20/bin/sh-> Bash ")

Or you can change the hello file to an executable file and run it directly "#! /Bin/bash "function, the system will automatically use the/bin/bash program to explain the execution of the hello file:

$ Chmod U + x hello
$./Hello

"$ Hello" is not directly used here because the current directory is not the default directory of the executable files of the current user, but it is insecure to set "." as the default directory.

It should be noted that, after the bash program is executed, another process is set up in Linux to run.

  • Variables and operations
  • Input and Output
  • Process Control
  • Function
  • Bash shortcut Variables and operations

    Let's take a look at the usage of the variables in Bash as a whole, and then analyze the differences between the usage of the variables in bash and those in C. All variables in bash cannot contain reserved characters, "-", and other reserved characters, nor spaces.

    Simple Variables
    In bash, variable definitions are not required. There is no definition process like "int I. If you want to use a variable, it can be used directly as long as it has not been previously defined. Of course, the first statement you use this variable should assign an initial value to him, it does not matter if you do not assign an initial value, but the variable is null (Note: It is null, not 0 ). It is not a good programming habit to grant initial values without variables. 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 Str
    STR = "Hello World"
    Echo $ Str

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

    1. When assigning values to variables, '=' cannot contain spaces on both sides;
    2. The end of a bash statement does not require a semicolon (";");
    3. Except for variable assignment and in the for loop statement header, the variable in Bash must be preceded by the "$" symbol, you can change the third line in the above program to "Echo Str" and try again to see what the result will be.
    4. Since the bash program runs in a new process, the variable definitions and assignments in the program do not change the values of variables with the same name in other processes or the original shell, and will not affect their operation.

    More detailed documents even mention that variables enclosed in quotation marks will not be interpreted by Bash as variables, such as '$ str', but will be seen as pure strings. In addition, the more standard variable reference method is like $ {STR}. $ STR itself is a simplification of $ {STR. In complex cases (where there may be ambiguity), it is best to use the representation.

    Since the variables in bash do not need to be defined, there is no type. A variable can be defined as a string or an integer. If an integer operation is performed on the variable, it is interpreted as an integer. If a string operation is performed on the variable, it is viewed as a string. See the following example:

    #! /Bin/bash
    X = 1999
    Let "x = $ x + 1"
    Echo $ x
    X = "Olympus ic" $ x
    Echo $ x

    There are several types of integer variable calculation: "+-*/%", which means the same as the word. Integer operations are generally implemented through the let and expr commands. For example, you can write the variable X by adding 1: let "x = $ x + 1" or X = 'expr $ x + 1'

    In comparison, the integer and string variables are different. For details, see the following table:

    Corresponding operation Integer Operation string operation
    Same-eq =
    Different-ne! =
    Greater than-GT>
    Less than-lt <
    Greater than or equal to-Ge
    Less than or equal to-le
    Blank-z
    Not empty-n

    For example:

    Compare whether the strings A and B are equal to write: If [$ A = $ B]
    To judge whether string a is null, write: If [-Z $ A]
    To determine whether integer A is greater than B, write: If [$ A-GT $ B]

    For more detailed documents, we recommend that you do not use-N when comparing strings! -Z to replace. (The symbol "! "Indicates reverse operation)

    In bash, variables are used not only to operate integers and strings, but also as file variables. Bash is the shell of the Linux operating system. Therefore, the system file must be an important object to be operated by bash, for example, if [-x/root] can be used to determine whether the/root directory can be accessed by the current user. The following table lists the operators used in Bash to determine file attributes:

    Operator meaning (true is returned if the following requirements are met)

    -E file already exists
    -F file: The file is a common file.
    -S file size is not zero
    -D file: The file is a directory.
    -R file can be read by the current user
    -W file can be written to the current user
    -X file can be executed on the current user
    -The GID mark of the-G file is set.
    -Ufile: The UID mark of the file is set.
    -O file belongs to the current user
    The Group ID of the-G file is the same as that of the current user.
    File1-nt file2 file file1 is updated than file2
    File1-ot file2 file file1 is older than file2

    Note: file, file1, and file2 in the preceding table indicate the paths of a file or directory.

    Local Variables
    If a variable is used in a bash program, the variable remains 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 by adding the local keyword when the variable is assigned the initial value for the first time, as shown in the following example:

    #! /Bin/bash
    Hello = Hello
    Function Hello {
    Local Hello = World
    Echo $ hello
    }
    Echo $ hello
    Hello
    Echo $ hello

    The execution result of this program is:

    Hello
    World
    Hello

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

    Differences between bash variables and C Variables
    Here, programmers who are not familiar with Bash programming but are very familiar with the C language summarize the issues that need to be paid attention to when using variables in the bash environment.

    1. When referencing a variable in Bash, you must add the "$" symbol before the variable (the first value assignment and the "$" symbol is not required in the for loop header );
    2. There is no floating point operation in bash, so there is no variable of the floating point type available;
    3. The comparison symbols of Integer Variables in bash are completely different from those in C language, and the arithmetic operations of integer variables must also be processed by let or expr statements;

    Input and Output

    Input, output, and error output
    In the character terminal environment, the concept of standard input/standard output is well understood. Input refers to the input of an application or command, whether on the keyboard or from another file; output refers to the information generated by the application or command; different from Windows systems, there is also a standard error output concept in Linux, which is mainly set for program debugging and system maintenance purposes, the error output is separated from the standard output, so that some advanced error messages do not interfere with normal output information, so as to facilitate the use of general users.

    In Linux: The standard input (stdin) is the keyboard input by default, the standard output (stdout) is the screen output by default, and the standard error output (stderr) by default, it is also output to the screen (the above STD indicates standard ). When using these concepts in bash, the standard output is generally expressed as 1, and the standard error output is expressed as 2. The following is an example of how to use them, especially standard output and standard error output.

    Input, output, and standard error output are mainly used for I/O redirection, that is, they need to change their default settings. Let's look at this example first:

    $ Ls> ls_result
    $ LS-L> ls_result

    The preceding two commands respectively redirect the LS command output to the ls_result file and append it to the ls_result file, instead of the output to the screen. ">" Indicates the redirection of the output (standard output and standard error output). Two consecutive ">" symbols, that is, ">" indicates that the output is appended without clearing the original one. Next, let's look at a slightly complex example:

    $ Find/home-name lost * 2> err_result

    This command adds a "2" and "2>" before the ">" symbol to redirect the standard error output. Some directories in the/home directory cannot be accessed due to permission restrictions. Therefore, some standard error outputs are stored in the err_result file. You can imagine what results will be produced by the find/home-name lost * 2> err_result command?

    If you directly execute find/home-name lost *> all_result, only the standard output is saved to the all_result file, what should I do if I want to save the standard error output to a file like the standard input? Let's look at the example below:

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

    In the above example, we will first redirect the standard error output to the standard output, and then redirect the standard output to the all_result file. In this way, all output files can be stored in files. To implement the above functions, there is also a simple Syntax:

    $ Find/home-name lost *> & all_result

    If the error information is not important, run the following command to avoid interference with useless error information:

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

    After returning, you can try the following redirection methods to see what the results will be. 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 "-". See the following example:

    $ (CD/source/directory & tar CF-.) | (CD/DEST/directory & tar xvfp -)

    This command is used to compress and decompress all files in the/source/directory, and quickly move all files to the/DEST/directory, this command will show a special advantage when/source/directory and/DEST/directory are not in the same file system.

    There are also several uncommon usage:

    N <&-indicates that N is disabled
    <&-Indicates that the standard input (keyboard) is disabled)
    N> &-indicates that output N is disabled.
    > &-Indicates that the standard output is disabled.

    Process Control
    Basic Process Control syntax in bash
    Bash contains almost all the control structures commonly used in C language, such as conditional branches and loops. The following describes them one by one.

    If... then... else
    The IF statement is used to determine and branch. Its syntax rules are very similar to the IF statement in C language. The basic structure is as follows:

    If [expression]
    Then
    Statments
    Fi

    Or

    If [expression]
    Then
    Statments
    Else
    Statments
    Fi

    Or

    If [expression]
    Then
    Statments
    Else if [expression]
    Then
    Statments
    Else
    Statments
    Fi

    Or

    If [expression]
    Then
    Statments
    Elif [expression]
    Then
    Statments
    Else
    Statments
    Fi

    It is worth noting that if you write the IF and then in a simple line, you must add a semicolon before the then, such as: If [expression]; the example below demonstrates how to use the if condition to determine the statement:

    #! /Bin/bash

    If [$1-GT 90]
    Then
    Echo "Good, $1"
    Elif [$1-GT 70]
    Then
    Echo "OK, $1"
    Else
    Echo "Bad, $1"
    Fi

    Exit 0

    In the above example, $1 refers to the first parameter of the command line, which will be explained in "special reserved words in Bash.

    For
    The for loop structure is different from the C language. In bash, the basic structure of the For Loop is:

    For $ VaR in [LIST]
    Do
    Statments
    Done

    $ VaR is a loop control variable, and [LIST] is a set to be traversed by $ var. The do/done pair contains the loop body, which is equivalent to a pair of braces in C. In addition, if do and for are written in the same line, you must add ";" before do ";". For example, for $ VaR in [LIST]; do. The following is an example of loop using:

    #! /Bin/bash

    For day in Sun mon Tue wed Thu Fri Sat
    Do
    Echo $ day
    Done

    # If the list is contained in a pair of double quotation marks, it is considered an element.
    For day in "Sun mon Tue wed Thu Fri Sat"
    Do
    Echo $ day
    Done

    Exit 0

    Note that in the preceding example, the variable day in the row where the for is located does not contain the "$" symbol, but is in the loop body, the line variable $ day in which ECHO is located must contain the "$" symbol. In addition, if it is written as for day without the subsequent in [LIST], day will retrieve all the parameters of the command line. Such as this program:

    #! /Bin/bash

    For Param
    Do
    Echo $ Param
    Done

    Exit 0

    The above program will list all command line parameters. The loop body of the for loop structure is contained in the do/done pair, which is also characteristic of the while and until loops.

    While
    The basic structure of the while loop is:

    While [condition]
    Do
    Statments
    Done

    Compile an example to verify this structure.

    Until
    The basic structure of the until loop is:

    Until [condition is true]
    Do
    Statments
    Done

    You can write an example to verify this structure.

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

    Case "$ Var" in
    Condition1)
    Statments1 ;;
    Condition2)
    Statments2 ;;
    ...
    *)
    Default statments ;;
    Esac

    The following example uses the case structure for Branch execution:

    #! /Bin/bash

    Echo "hit a key, 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 ";;
    Esac

    Exit 0

    The read Statement in the fourth row of "read keypress" in the preceding example indicates that the input is read from the keyboard. This command will be explained in other advanced issues of bash in this handout.

    Break/continue
    Anyone familiar with C programming is familiar with break statements and continue statements. Bash also has these two statements, and their functions and usage are the same as those in C. The break statement can completely jump out of the current loop body, the continue statement can skip the remaining part of the current loop and directly enter the next loop.

    Function
    Function usage
    Bash is a relatively simple scripting language. However, bash also provides function-defined functions to facilitate structural design. The function definition in Bash is very simple. You just need to write it like this:

    Function my_funcname {
    Code block
    }

    Or

    My_funcname (){
    Code block
    }

    The second method above is closer to the C language. Bash requires that the function must be defined before the function is used. This is different from the function method described in header files in C.

    The further question is how to pass parameters to the function and obtain the return value. The definition of function parameters in Bash does not need to be defined in the function definition. Instead, you only need to use the bash reserved variable $1 $2 when the function is called... bash return values can be specified by the Return Statement to return a specific integer. If no return statement explicitly returns a return value, the returned value is the result of executing the last statement of the function (usually 0. If the execution fails, an error code is returned ). The Return Value of the function is passed through $? Reserved Words. Here is an example of using a function to calculate the integer square:

    #! /Bin/bash

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

    Square $1
    Result = $?
    Echo $ result

    Exit 0

    Bash shortcut
    About the shortcut keys of bash in the console

    CTRL + u Delete All characters before the cursor
    CTRL + D delete a character before the cursor
    CTRL + k Delete All characters after the cursor
    CTRL + H delete a character after the cursor
    CTRL + t change the order of the first two characters of the cursor
    CTRL + a move the cursor to the front
    CTRL + e move the cursor to the end
    CTRL + p command
    CTRL + N next command
    CTRL + S lock Input
    CTRL + q unlock
    CTRL + F move the cursor to the next character
    CTRL + B move the cursor to the previous character
    CTRL + X mark a location
    CTRL + C clear the current input

  • 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: info-contact@alibabacloud.com 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.