Shell Script Basics

Source: Internet
Author: User
Tags arithmetic define local file permissions

变量:命名的内存空间 数据存储方式: 字符: 数值:整型,浮点型 变量:变量类型 作用: 1、数据存储格式 2、参与的运算 3、表示的数据范围 类型: 字符 数值:整型、浮点型 强类型:变量不经过强制转换,它永远是这个数据类型,不允许隐式的类型转换。 一般定义变量时必须指定类型、参与运算必须符合类型要求; 调用未声明 变量会产生错误 如 java,c# 弱类型:语言的运行时会隐式做数据类型转换。无须指定类型, 默认均为字符型;参与运算会自动进行隐式类型转换; 变量无须事先定义可直接调用 如:bash 不支持浮点数,php 变量命名法则: 1、不能使程序中的保留字: 例如if, for 2、只能使用数字、字母及下划线,且不能以数字开头 3、见名知义 4、统一命名规则:驼峰命名法 变量的种类 根据变量的生效范围等标准划分下面变量类型: 局部变量:生效范围为当前shell进程;对当前shell之外的其它shell进程, 包括 当前shell的子shell进程均无效 环境(全局)变量:生效范围为当前shell进程及其子进程 本地变量:生效范围为当前shell进程中某代码片断,通常指函数 位置变量:$1, $2, ...来表示,用于让脚本在脚本代码中调用通过命令行传递给它的参数 特殊变量:$?, $0, $*, [email protected], $#,$$ 局部变量 变量赋值:name=‘value’ 可以使用引用value:

(1) can be a direct string; Name= "Root"
(2) Variable reference: name= "$USER"
(3) Command reference: Name= COMMAND name=$
Variable reference: ${name} $name "":
A weak reference in which the variable reference is replaced with the variable value ':
Strong references, where the variable references are not replaced with the variable values, while the original string is persisted
Show all variables that have been defined: set
Delete variable: unset name

environment variable variable declaration, assignment: Export name=value declare-x name=value variable reference: $name, ${name} Show all environment variables: env Printenv Export declare-x Delete variable: unset name bash built-in environment variable: PATH SHELL U SER UID HOME PWD shlvl LANG MAIL HOSTNAME histsize-read-only variable: declares only, but cannot modify and delete declared read-only variables : readonly name Declare-r name View read-only variable: readonly–p positional variable: A parameter that is passed to the script through the command line is called in the script code. A. : corresponding to the 1th and 2nd parameters, Shift [n] Position $: command itself $*: All parameters passed to the script, all parameters are combined as a string [email protected]: All parameters passed to the script , each parameter is a stand-alone string $#: The number of arguments passed to the script [email protected] $* only when the double quotation marks are wrapped up will have a difference set--empty all positional variables process use exit Status to report success or failure 0 for success, 1-255 for failed $? Variables save the most recent command exit status for example: Ping-c1-w1 hostdown &>/dev/null echo $?bash custom exit status code Exit [n]: Custom Exit form          Code Note: Once the exit command is encountered in the script, the script terminates immediately; the terminating exit status depends on the number following the Exit command Note: If the script is not assigned an exit status code,  The exit status code for the entire script depends on the status code of the last command executed in the script. The arithmetic operation in bash: Help let +,-, *,/,% modulus (take away), * * (exponentiation) to implement arithmetic operations: (1) Let var= arithmetic expression (2) var=$[arithmetic expression] (3) var=$ ((Arithmetic expression)) (4) var=$ (expr arg1 arg2 arg              3 ...) (5) declare–i var = numeric (6) echo ' Arithmetic expression ' |      The BC multiplication symbol needs to be escaped in some scenarios, such as * Bash has built-in random number generator: $RANDOM (0-32767) echo $[$RANDOM%50]: 0-49 random number Enhanced assignment:           + =,-=, *=,/=,%= let Varopervalue for example: Let count+=3 since add 3 self-assignment self-increment, self-reduction: let Var+=1          Let var++ let Var-=1 let var--true, False 1, 0 with: 1 and 1 = 1          1 with 0 = 0 0 with 1 = 0 0 with 0 = 0 or: 1 or 1 = 1 1 or 0 = 1 0 or 1 = 1 0 or 0 = 0 Non:!! 1 = 0! 0 = 1 Short-circuit operation short-circuit and the first is 0, the result must be 0 first is 1, the second must participate in the operation Short circuit or the first is 1, the result must be 1 First 0,    The second must be involved in an operation XOR: ^            XOR two values, the same is false, the difference is true to determine whether a requirement is satisfied, need to be implemented by the test mechanism to implement a dedicated test expression needs to be assisted by the test command to complete the test process Evaluation Boolean declaration, in order to use in the conditional execution if true, then return 0 if False, then return 1 Test life Order: test expression [expression] [[expression]] Note: You must have a white space character before and after EXPRESSION depending on the exit status, the command can run conditionally &A  mp;& represents conditional and then | | Represents a conditional or ELSE example: Grep-q no_such_user/etc/passwd \ | |  Echo ' No such user ' No such user ping-c1-w2 station1 &>/dev/null \ > && echo "Station1 is up" \ > | | (Echo ' station1 is unreachable '; exit 1) An example of the long format of the station1 is up Test command: Test "$A" = = "$B" &&   echo "Strings is equal" test "$A"-eq "$B" && echo "integers is equal" abbreviated format example: ["$A" = = "$B"] && echo "Strings is equal" ["$A"-eq "$B"] && echo "Integers is equal" bash numerical test-          v Var variable var sets whether the numeric test: whether-GT is greater than-ge is equal to-eq is equal toWhether the-ne is not equal to whether the-lt is less than-le is less than or equal to bash's string test string test: = = is equal to > ASCII code greater than ASCII                Whether < is less than = is not equal to whether the =~ left string can be matched by the pattern on the right note: This expression is typically used in [[]]; extended regular expressions -Z "string" string is empty, empty is true, NOT NULL is False-n "string" string is not empty, not empty is true, empty is false note: The operands used for string comparisons should use quotation marks for existence Test-a file: The same-e-e file: The existence of the test, the existence of the true, otherwise false existence and category test-B file: Whether it exists and is a block device file, C file: exists and is a character device file-D FI  LE: Is present and is a directory file-f file: exists and is a normal file--H file or-L file: exists and is a symbolic link file-P: exists and is named pipe file-S: exists and is a socket file File Permissions Test:-R-File: exists and is readable-W file: exists and writable-X file: exists and executable file special permissions test:-u file: Exists and has suid permissions-G FI  LE: Exists and has the Sgid permission-K file: Is present and has the properties of the Sticky Permission bash file test file size test:-S-file: exists and non-empty files are open:-T FD:     Whether the FD file descriptor is already open on a terminal-N file: Whether the file has been modified since the last read-O file: Whether the current valid user is a file owner-G: The current valid user is a file group Binocular test: FILE1-EF File2:file1 whether the FILE2 hard link file1-nt file2:file1 is new to FILE2 (mtime) File1-ot File2:file1 is older than FILE2 bash group Test conditions First way: COMMAND1 && COMMAND2 and COMMAND1 | | COMMAND2 or!          COMMAND not as: [[R File]] && [[w file]] second way: Expression1-a EXPRESSION2 and Expression1-o EXPRESSION2 or!  EXPRESSION must be performed using a test command

Example: [-Z "$HOSTNAME"-o $HOSTNAME "==\
" Localhost.localdomain "] && HOSTNAME www.xxx.com
[ -f/bin/cat-a-x/bin/cat] && cat/etc/fstab

Use the Read command to accept input using read to assign the input value to one or more shell variables-p Specifies the prompt to display-s silent input, typically used for password-n to specify the input character length n -d ' character ' input terminator-T n timeout is n second read value from standard input, assigning a variable to each word all remaining words are assigned to the last variable read-p "Ent     ER a filename: "FILE Bash expands command line to split the command line into a single command word expand alias expand curly Brace declaration ({}) expand Tilde Declaration (~) command Replace $ () and" "to divide command line into command word again          Expand File Wildcard (* 、?、 [ABC] and so on) prepare i/0 redirect (<, >) Run command to prevent extension of backslash (\) causes subsequent characters to be interpreted as intended $ echo Your cost: \$6.00             Your Cost: $6.00 quotes to prevent extended single quotes (') to prevent all extended double quotes (") also prevent all extensions, except for the following cases: $ (dollar sign)-variable extension ' (anti-quote)-command substitution \ (backslash)-suppresses single character expansion! (exclamation mark)-history command to replace Bash's profile can be divided into 2 categories according to the effective scope: global configuration:/et C/PROFILE/ETC/PROFILE.D/*.SH/ETC/BASHRC Personal profile ~/.bash_profile ~/.bashrcshell login 2 ways to cross Mutual Login: (1) Enter the account password directly via terminal (2) User execution order using "su-username" switch:/etc/profile---/etc/profile.d/*. SH--~/.bash_profilE--~/.BASHRC---/ETC/BASHRC non-interactive login: (1) Su UserName (2) The terminal opened under the graphical interface ( 3) Execute script (4) Any other bash instance execution order: ~/.BASHRC----------/etc/profile.d/*.sh profile class is functionally divided, There are two types of profiles: Profile and BASHRC: The configuration of the shell for the Interactive logon:/etc/profile,/etc/profile.d/*.sh Personal: ~/.bash_p Rofile function: 1. Used to define environment variables 2. Run a script or command BASHRC class BASHRC class: Provides configuration global for non-interactive and interactive logon shells:/etc/bashr C Personal: ~/.BASHRC function: 1. Define command aliases and Functions 2. Define local variable edit the profile takes effect when you modify the profiles and BASHRC files to take effect both ways    Method 1 Restart Shell Process 2. or source PS. ~/.bashrcbash exit task saved in ~/.bash_logout file (user)         When you exit the login Shell, run to: Create an automatic backup to clear temporary files $ variable: h:hashall, when this option is turned on, the shell hashes the path where the command is located, avoiding querying every time.        The h option is turned off by the set +h i:interactive-comments, including this option to indicate that the current shell is an interactive shell.     The so-called interactive shell, in the script, I option is off. M:monitor, turn on the monitor mode and you can use the jobControls to control the process of stopping, continuing, backstage, or foreground execution. B:braceexpand, the curly brace extension h:history,h option opens, you can expand the commands in the History list, you can do so by! Exclamation marks, such as "!!" Return on a recent history command, "!n" returns the nth historical command bash-x Debug execution time, display the number of preceding + represents the depth of statement nesting when you export the article, you can use "" to preserve its formatting pstrss-p see all parent-child process trees echo $$ Show current process number local variable working range: Current process, cannot cross process and session, cannot pass global variable to child process and parent process can be passed down, cannot be passed up ENV command can display environment variable set can display all variables and functions $bashpid subprocess id$ PPID Parent Process Idreadonly read-only constant, cannot be unset deleted, but it is released with the end of the current shell-P can display constants Declare-r can also display constants used once (one time) can pass () through the child process shell influence, exit subprocess After modifying the invalid PS: (umask 666; Touch/data/f1 at this time the file is 000 permissions, but the parent shell does not affect) {command} will affect the current shell, will not open the sub-shellps:x=1;echo $$; (Echo $$;echo $x; X=2;echo $x); Echo $x 1323 1323 1 2 1 () is different from a real child shell, () is equivalent to opening a child shell but is not really opening parameters over 9 ${ } ps:10 above parameter #{10} script set--empty parameters to establish a soft connection can change the display of $0 or not 0 is only related to the last one, the last success is $0, if there is a grammatical error, you need to self-study to see the source of the error by exit + number can be modified to return the number $_            Show last argument parenthesis usage: command execution within parentheses does not affect the current shell, the one-time task {} Does not open child shell will affect the current shell environment Shift command: can implement parameters of the queue expulsion script in shift 12345->2345 Shift 2 12345->345expr plus arithmetic ps:expr 3 \*2 (middle plus space indicates parameter * number to escape) expr 1 + 2 Do addition operation a B XOR interchange A=$[a^b] Get middle value b=$[a^b] b get original a a=$[a^b] a get the original            b Echo $a $b complete interchange true simply return the correct result Ps:trus $?            0 false return error result Ps:false $? 1 when using variables in parentheses, it is usually recommended to add "" to avoid the effect of Null characters false | | {echo cmd1; echo cmd2;} False to execute cmd1 and cmd2 false | | (Cho cmd1; Echo cmd2; If False then execute cmd1 and cmd2 true | | {echo cmd1; echo cmd2;} True to not execute cmd1 and cmd2 true | | (Echo cmd1; Echo cmd2; If False, CMD1 and cmd2 false are not performed | | {echo cmd1; exit;} Execute this statement in the script when using {} This allows the script to exit, if using () can not exit, () opened a new child shell is empty and empty values are different

Shell Script Basics

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