Bash getting started

Source: Internet
Author: User
Tags uppercase letter
Shell types:Sh-Bourne shell CSH or tcsh-C shell Korn-Korn shell bash-GNU Bourne-again shell
1. Simplest ColumnExample #! /Bin/bash # This is a very simple example echo Hello World
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. In the bash program, start with "#" (note: "!" is followed by "!". (Except) many parts from the beginning to the end of the line are considered as program comments. The echo statement function is to output the strings after Echo to the standard output.
Run this program: 1. $ bash hello or $ sh Hello 2. 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
2. input, output, and error outputIn 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 ).
$ Ls> ls_result $ LS-L> ls_result LS command result output RedirectionNeutralization to the ls_result File AppendTo the ls_result file instead of output to the screen. ">" Indicates the redirection of the output (standard output and standard error output). Two consecutive ">" symbols, that is, ">>" indicates that the original output is not cleared and the output is appended.
$ Find/home-name lost * 2> err_result: This command adds "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.
$ Find/home-name lost *> all_result 2> & 1 first redirects the standard error output to the standard output, and then redirects the standard output to the all_result file. In this way, we can store all the output to the file in a simpler way: $ find/home-name lost *> & all_result helps you avoid interference with many useless error messages:
$ Find/home-name lost * 2>/dev/null
Another very useful redirection operator is "-"
$ (CD/source/directory & tar CF -.) | (CD/DEST/directory & tar xvfp-) This command indicates to compress and decompress all files in the/source/directory, quickly move everything to the/DEST/directory
3. Variables
Example :#! /Bin/bash # Give the initialize value to STR = "Hello World" Echo $ Str
Note: 1. When values are assigned to variables, '=' is not allowed between the left and right sides. 2. A semicolon (";") is not required at the end of the bash statement. 3, except for assigning values to variables and in the for loop statement header, bash variables must be preceded by the "$" symbol, 4, since the bash program runs in a new process, the variable definition and value assignment in this 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.
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.
Example :#! /Bin/bash x = 1999 let "x = $ x + 1" Echo $ x = "Olympus ic" $ X echo $ x
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'
Corresponding operation Integer Operation String operation
Same -EQ =
Different -Ne ! =
Greater -GT >
Less -Lt <
Greater than or equal -Ge
Less than or equal -Le
Not empty

The operator used in Bash to determine file attributes:
Operator Meaning (true is returned if the following requirements are met)
-E File File already exists
-F File File is a common file.
-S file File size is not zero
-D File File is a directory
-R File The file can be read by the current user.
-W File File files can be written to the current user.
-X file The file can be executed by the current user.
-G File The GID mark of the file is set.
-U File File uid flag is set
-O file The file belongs to the current user.
-G File The Group ID of the file is the same as that of the current user.
File1-nt file2 File file1 is newer than file2
File1-ot file2 File file1 is older than file2

Local variableWhen a variable is assigned an initial value for the first time, the local keyword can be added to declare a local variable.
#! /Bin/bash Hello = Hello function Hello {local Hello = World echo $ Hello} echo $ hello echo $ Hello the program's execution result is: Hello World Hello
4. Basic Process Control syntaxThe IF... then... else if statement is used to determine and branch. Its syntax rules are very similar to the IF statement in C. 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
Note: If you write the IF and then in a simple line, you must add a semicolon before the then, such as: If [expression]; then...
For LoopFor $ VaR in [LIST] Do statments done Note: Do and for are written in the same row and must be prefixed ";". For example: For $ VaR in [LIST]; do
#! /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.
#! /Bin/bash for day in "Sun mon Tue wed Thu Fri Sat" Do echo $ day done
If it is written as for day without the in [LIST] Part, day will retrieve all the parameters of the command line.
#! /Bin/bash for Param do echo $ Param done exit 0
While [condition] Do statments done
UtilUntil [condition is true] Do statments done
CaseCase "$ Var" in condition1) statments1; condition2) statments2;... *) default statments; esac
Example #! /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"; the read Statement in esac exit 0 "read keypress" indicates reading input from the keyboard
Support for break/continueYou know
5. FunctionsThe definition of function parameters in function my_funcname {code block} Or my_funcname () {code block} 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. Example #! /Bin/bash square () {Let "res = $1 * $1" return $ res} square $1 result = $? Echo $ result exit 0

6. Special Reserved Words in bash Reserved variableThe $ IFS Variable contains the delimiter used to separate input parameters. The default Delimiter is space. The $ home variable stores the root directory path of the current user. The $ PATH variable stores the default path string of the current shell. $ PS1 indicates the first system prompt. $ PS2 indicates two system prompts. $ PWD indicates the current working path. $ Editor indicates the Default Editor name of the system. $ Bash indicates the path string of the current shell. $0, $1, $2,... indicates the 0th, first, and second parameters that the system sends to the script program or the script program to the function. $ # Indicates the number of command parameters of the script program or the number of function parameters. $ Indicates the process Number of the script program. It is often used to generate a temporary file with a unique file name. $? Indicates the return status value of the script program or function. The normal value is 0. Otherwise, it is a non-zero error number. $ * Indicates all Script Parameters or function parameters. [Email protected] is similar to $ *, but safer than $. $! Indicates the process Number of the last process running in the background.
Random Number
$ Random: randomly generates an integer between 1 and 65536.
Special Operations on variables$ {Var-default} indicates that if the variable $ VaR is not set, the status of $ VaR is not set, and the default value default is returned. $ {Var = default} indicates that if the variable $ VaR has not been set, the default value is default. $ {Var + otherwise} indicates that if the variable $ VaR has been set, the value of otherwise is returned; otherwise, null is returned ). $ {Var? Err_msg} indicates that if the variable $ VaR has been set, the value of the variable is returned. Otherwise, the subsequent err_msg is output to the standard error output. These usages are mainly used to extract useful information from the file path string: $ {var # pattern}, $ {var # pattern} is used to strip the shortest (longest) from the variable $ var) the leftmost string that matches pattern. $ {Var % pattern}, $ {var % pattern} is used to strip the rightmost string that matches pattern in the shortest (longest) from the variable $ var. In addition, the following operations are added to bash 2: $ {var: POS} indicates removing the first POS character from the variable $ var. $ {Var: pos: Len} indicates the first LEN character of the remaining string after the first POS character is removed from the variable $ var. $ {Var/pattern/replacement} replaces the First Occurrence Pattern pattern in the variable $ VaR with the replacement string. $ {Var // pattern/replacement} indicates replacing all pattern modes in the variable $ VaR with the replacment string.

7. Other advanced problems in bash Processing of return values in bash
Whether it is processing the return value of the bash script in shell or processing the return value of the function in the script, it uses "$? "System variables. Bash requires that the return value must be an integer. The return statement cannot be used to return string variables.
Use Bash to design a simple user interfaceSelect VaR in [LIST] Do statments use $ var done bash adds all the items in [LIST] To the number column on the screen and waits for the user to select. After the user makes the selection, the variable $ var contains the selected string 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
Bash program debuggingWith the bash-x bash-script command, you can view where an erroneous bash script is located and help the programmer find the errors in the script. In addition, the trap statement can be used to print some variable values when the bash script exits due to an error for the programmer to check. The trap statement must be followed "#! The first unannotated code after/bin/bash is written by the trap command: Trap 'message $ checkvar1 $ checkvar2' exit

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.