Bash Script Programming Basics

Source: Internet
Author: User

1. What is Shell scriptshell script is to use the shell's function to write a "program", the program is to use a plain text file, some shell syntax and commands written inside. 2. Script or program source files are plain text files. 3. The execution of a script or program is generally done in two ways: Compile execution: Preprocessing----and compile-to-compile----the execution of a computer language. The compiler compiles the target code one at a time into the target program, and then the target program is run by the machine. such as: Pascal,c,c++ and other languages. Efficiency is higher than interpretation execution. Explanation execution: The interpreter is involved in the whole process of running, one line at a time, the program is composed of a set of execution and data. 4.bash execution of the 1> command is performed from top to bottom, left-to-right analysis and execution of the 2> command, where multiple whitespace between commands and arguments is ignored 3> blank lines are ignored 4> not read a enter character, start executing the program 5> "# As an annotation, any data added to the # will be treated as an annotation 6>shell script  ends with *.sh, and a shell script can be executed with x permission 7>bash shell program   must be executed by the bash process to execute variables in 5.bash shell , what is a variable? A variable is the amount of variation in a program, and a variable is used to name the memory space. Bash's variable types are as follows: Local variables: The current shell process, environment variables: the current shell process and its child processes, local variables: a function execution procedure, positional parameter variables: references to parameters passed to the script in the script; arguments passed to the function in the function; Special variables: $? : The return value of the previous command execution state: program execution may have two return values:1.  program execution Results 2.  program state return (0-255) 0  Execute error (1-255  system reservation) for correct 1,2,127; $# : Gets the total number of parameters in the current shell command line $*: Gets all parameters of the current shell   "$1 $2 $3  ..., under IFS control [email protected]: All parameters of this program   "$1″ " $2″  "$3″ " ... ", not controlled by IFS $0  gets the file name of the currently executing shell script $n  gets the nth parameter value of the currently executing shell script, n=1.. 9$$  gets the current shell's process number (PID) $!  The state result of the PID custom script executing the previous instruction: Exit [n] Note: The exit command is executed anywhere in the script to terminate the current shell process 6. Variable type: Numeric, character, where the value can be divided into integers and floating-point numbers, characters are divided into ASCII and plain text characters. 7. Function of variable type: storage space, numerical operation, definition of storage format 8.bash variable use characteristics: weak type, without prior declaration; 9. Naming rules for variables:      the first character must be a letter (A-Z, A-Z)       cannot have spaces in the middle, you can use underscores (_)       cannot use punctuation marks        cannot use keywords in bash (help command to view reserved keywords) 10. Local variables and environment variables 1> Local variables: varname=value: Scopes are available for the entire bash process. Where varname is the variable name, = is an assignment symbol, value is a reference to the values: the weak reference:  "",  its internal variable reference is replaced with the variable value; Strong reference: ", the variable reference of its variable will keep the original character; Command reference: ' Commands ',  $ (command), which refers to the execution result of the commands, declares the integer:declare -i name[=value]let name=value2> environment variable: The local variable that is "exported", The scope is the current shell process and its child processes, and there are two common definition methods that cannot affect the environment variables of their parent processes: Export name[=value]declare -x name[=value] View all environment variables: env, printenv, export  the destruction of environment variables is also used unset   Name11. The life cycle of a variable, when a shell process terminates, the variable is automatically destroyed, or the variable is manually destroyed, you can use the unset  variable name

Okay, now we're going to go into the world of bash shell, first we implement the output of the string through the bash shell. For the convenience of writing Shelll script later, we recommend that you create a ~/scripts directory to store scripts.

650) this.width=650; "title=" 02.png "alt=" wkiol1x1fwjid5zqaabk2r9zlny677.jpg "src=" http://s3.51cto.com/wyfs02/M01/ 73/1b/wkiol1x1fwjid5zqaabk2r9zlny677.jpg "/>

Where #/bin/bash is a fixed format for Shell programming to declare that the syntax in this file is using Bash's syntax, and when the program executes, it can load bash's associated environment configuration file. The entire script, except the first "#" is used to declare the shell, the other # is the "annotation" purpose. In order to conveniently view the shell script later, it is recommended to write the function of the shell, author, time and other key rest, as shown above.

Common options for bash:

-N: Check for syntax errors in the script;

-X: Debug Execution script;

Check for syntax errors in the script and nothing, stating that there are no syntax errors.

[Email protected] scripts]# bash-n first.sh

Debug Execution Script

[Email protected] scripts]# bash-x first.sh

+ echo-e ' Welcome to Linux shell script.\a \ n '

Welcome to Linux shell script.

+ Exit 0

Custom Script Status results:

Exit [n]

Note: Executing the exit command at any location in the script terminates the current shell process

Custom status return value is 1

650) this.width=650; "title=" 04.png "alt=" wkiom1x1ggsiu2joaabzu99nljq993.jpg "src=" http://s3.51cto.com/wyfs02/M02/ 73/1e/wkiom1x1ggsiu2joaabzu99nljq993.jpg "/>

After executing the program review, the 1 instructions are correct.

650) this.width=650; "title=" 03.png "alt=" wkiol1x1gjjtwz51aaa2rchwoxe700.jpg "src=" http://s3.51cto.com/wyfs02/M02/ 73/1b/wkiol1x1gjjtwz51aaa2rchwoxe700.jpg "/>

The difference in how script executes (Bash,source,.)

Take the following name.sh script as an example

650) this.width=650; "title=" 05.png "alt=" wkiol1x1hwawadygaabity56yci142.jpg "src=" http://s3.51cto.com/wyfs02/M00/ 73/1b/wkiol1x1hwawadygaabity56yci142.jpg "/>

[[Email protected] scripts]# sh name.sh//First execute script with bash

Please input your first name:l

Please input your last Name:ys

Your Full Name Is:lys

650) this.width=650; "title=" 06.png "alt=" wkiom1x1hx-xq-vgaaaq_txqatk848.jpg "src=" http://s3.51cto.com/wyfs02/M00/ 73/1e/wkiom1x1hx-xq-vgaaaq_txqatk848.jpg "/>

See there is no way to set a good variable firstname,lastname No value, this is why? When you use the direct execution method to process, The system will give a new bash to execute the commands inside the name.sh, so our variable firstname,lastname is actually executed in the new bash, and after the child process is complete, the variables or actions within the subprocess will end without being passed back to the parent process. Below we use source or. To perform a look.

650) this.width=650; "title=" 07.png "alt=" wkiom1x1htyimijzaabqfxgjfn8287.jpg "src=" http://s3.51cto.com/wyfs02/M00/ 73/1e/wkiom1x1htyimijzaabqfxgjfn8287.jpg "/>

I echo $firstname $lastname is worth it. Because source and. are executed in the parent process, the actions will take effect within the original bash. This is clear bash,source and. The difference between executing shell scripts.

condition Test :

How do I test a shell script? We can also use test expressions in addition to the status results of running commands. When we want to detect certain files or related properties on the system, we can use the test command to display the entire result.

1. For a comparison of two integers, for example, NUM1, num2

The meaning of the test sign represents

-eq Two numbers equal

-ne Two-digit range

-GT NUM1 greater than num2

-lt                                                                               num1 less than num2

-ge                                                                            NUM1 is greater than or equal to num2

-le num1 less than or equal to num2

2. String data, the larger the ASCII value, the greater the value of the character comparison

The meaning of the test sign represents

-Z string is empty, NULL is true, otherwise false

-N string is not empty, not empty "true", Empty is "false"

Test STR1 = str2 Determines whether str1 equals str2, equals true, not equal to False

Test STR1! = str2 Determine if str1 is not equal to str2, not equal to true, equals false

3. Tests between two files, such as Test file1 and File2

The meaning of the test sign represents

-nt determine whether file1 is newer than file2

-ot determine if file1 is older than file2

-ef determine if file1 and File2 are the same file

4. Detection of file permissions

What the test parameters mean

-R detects if this file exists and has "readable" permissions

-w                                                                              detects if this file exists and "writable" permission

-x                                                                              detects if this file exists and the executable permission

-U detects if this file exists and "SUID" permission

-G detects if this file exists and "SGID" permission

-K detects if this file exists and "Sticky bit" permission

-S detects if this file exists and is "not a blank file"

-O Whether the current user is the owner of the specified file

-G Whether the current user is a generic group of the specified file

5. Identification of file types

The meaning of the parameter representation

-E exists or is true, otherwise false

-F Whether the file name is a normal file

-D file exists and is directory

-B exists and is a block device file

-C is present and is a character device file

-S exists and is a socket file

-P is present and is a pipe file

-L exists and is a linked file

Special Equipment:

/dev/null: Empty, bit buckets, swallow all data, and discard directly;

/dev/zero: Spit out a bunch of 0

This article is from the "Genius from Repetition" blog, please be sure to keep this source http://laoli110.blog.51cto.com/9136611/1694464

Bash Script Programming Basics

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.