Shell script Programming

Source: Internet
Author: User
Tags arithmetic arithmetic operators switch case

Shell script Programming 1. Basic concepts
    • In the shell # as a comment, using exactly the same method as in C //
    • The shell can be ; executed by executing two commands in the same line, such asls ; pwd
    • The script is executed sequentially, one sentence at a line to explain the execution
2. Use of variables

Variables are divided into global environment variables and private variables (that is, local environment variables), for the environment variables, see the Linux environment variable detailed

    • A shell program inherits all of its parent shell's global environment variables (that is, the export variable) and can override it without affecting the parent shell
    • The variables in the shell are untyped. The shell does not support floating-point type only support integer and string type, judge the standard: The variable contains only the number is the integer type, contains the other is the character is the string type
    • Variables can be defined at any time in the shell script, especially in the syntax of bash "=" cannot have spaces on either side of the value, and there are no spaces in the middle of the variable values, and some words are enclosed in single quotes.
test=123    #局部环境变量一般用小写export TEST=123#全局环境变量一般用大写export MYNAME=‘XIAO BA WU‘#变量值有空格,要用单引号围起来export#也可以这样把前面的局部变量导出到全局
    • In addition, as with C, variables must be defined and reused. If an undefined variable is used, it does not give an error, which is equivalent to calling a variable with a null value.

    • In the shell, it is not possible to get the value of a variable directly from the variable name, because the string in the shell can be unquoted, so the system cannot tell if it is a string or a variable name, so it $ gets its value by referencing the variable name. When the variable name is the right value, the system can directly determine it as a variable without adding$

value1=value2   //value1的值为字符串"value2"value1=$value2//value1的值为value2的值
    • In addition, the judgment of the variable name is space-sensitive, when the following occurs, in order for bash to correctly identify the variable name, you must use {} to enclose the variable name, which is a good habit
name=123name1=456echo$name1#打印name1的值echo$name11#打印name11的值(空值)echo${name}11#打印name的值 
    • When we need to end a string variable and then continue with a few characters, we can:
name=‘aa bb cc d‘name=$name‘d ee‘
    • $In the shell is the keyword, if you want to display the symbol in the string $ , you must add \ .

    • In the shell, we can assign the return value of a command to a variable using the anti-quote ' (the key that is located on the keyboard), such as:

PATH=`pwd`
3. Input and output
    • Echo can print the string directly, and the general situation does not need to surround it with single/double quotes. However, when single/double quotation marks appear in a string, in order to avoid ambiguity, a different quotation mark must be used to enclose
echo#一般情况下直接打印echo"let‘s go"#字符串里单引号,则用双引号包裹echo‘he says "shell is easy"‘#字符串里双引号,则用单引号包裹
    • By default, Echo will automatically add a newline character after the string is printed. If you want to cancel this feature, you can add parametersecho -n
    • We can redirect the output and export the return value of the instruction to a specified file by using > (overwrite write) or >> (append write)
pwd > /home/root/path.txt       #把pwd指令的返回值覆盖写入文件echo$i >> /home/root/log.txt   #把某个变量值追加写入文件
    • Similarly, we can redirect the input and import the contents of the file into the command (as a parameter of the command) by using < or << . To tell the truth. Input redirection is rarely used, the main is the command can be directly with the file name as parameters, why redirect it ....
4. Script entry and exit into script exit script

When the last sentence of the script is executed, it will automatically exit

    • Each command in the shell, at the end of execution, is returned to the shell with a return value of 0-255 integer value, general 0 for successful execution, and a positive number to indicate an error occurred
    • We can use it $? to get the return value of the last execution command.
    • Scripts can also be exited by us, often used in error handling, in the way exit var that VAR can be the return value of the script we specify when we exit
5. Data Manipulation Pipeline

The function of a pipeline is to use the return value of a command as a parameter to another command

    • In fact, there is no pipeline, with the middle variable can also achieve this function, but too bloated, or pipeline good. The following statement executes the Command1 first, the result is executed as a parameter command2, and the results are executed as parameters Command3
command1 | command2 | command3
Mathematical operations

Because a variable in the shell can be a string or a shape, it hurts to operate.

    • The most primitive method is to use the expr command, which is especially painful. Use the following, not only to get the output of expr using the anti-quotes, but also to use the backslash before the operator, because many arithmetic operators are keywords in the shell (such as the multiplication operator below)
var1=1var2=2var$var1$var2`
    • A new approach was introduced in bash, where the shell automatically treats the part of &[] as a mathematical operation and does not misunderstand the arithmetic operator
var1=1var2=2var=$[$var1$var2]
    • The method described earlier is only used for shaping operations, and in order to support floating-point operations in the shell, a special instruction BC, bash Calculator, must be used. As below, pass parameters to BC by pipe, use scale=4 to specify the result to keep several decimals
var1=1var2=3var=`echo"scale=4; $var1 / $var2" | bc`
6. Judging and looping structure if statement
    • The IF statement in the shell is structured as follows, which determines the return value of the Command1, and if 0 (that is, the command executes successfully) executes Command2, Command3; if 1 does not execute
if commandAthen    command1    command2fi#另一种风格的写法ifthen    command1    command2fi
    • Of course, there are also else in the shell, as well as ElseIf, with the following usage:
if commandAthen    command1else    command2fiif commandAthen    command1elif commanBthen    command2elif commandCthen    command3fi
    • Switch case can also be used to replace if else when multiple judgements are required
case$USRinroot)    echo root    echo oh!;;jack)    echo jack;;peter | ben)            #满足jack或ben    echo hah! hah!;;*)                      #星号代表默认情况    echo error;;esac
Test statement
    • The test command is a good companion to the IF statement, which is commonly used to determine whether the condition is satisfied, satisfies the return 0, and does not satisfy the return 1;test that can be used to compare: value, string, File/path. Common uses are:
if test conditionthen    commandsfi#bash支持的另一种格式,本质也是调用了test,千万要注意在condition和方括号之间加空格if [ condition ]then    commandsfi
    • When test is used for numeric comparisons, the basic format is var1 参数 var2 , as follows, there are many specific parameters, you can check the Internet
if$var1-eq$var2#判断var1和var2变量值是否相等if$var1-gt2#判断var1的变量值是否大于2
    • When test is used for string comparisons, the basic format is also available to use for var1 符号 var2 [[ ]] regular matching
if [ $string1 = $string2 ] #判断变量string1和string2值是否相等if [ $USR = !root ] #判断变量USR值是否不等于rootif[[ $USR == r* ]] #判断变量USR值是否以字母r开头
    • When test is used to determine the status of files and directories, the basic format is as 参数 filepath follows, there are many specific parameters, you can check the Internet
if-d$MYPATH#判断位于$MYPATH的文件是否存在,并且是个目录if-e$MYPATH#判断位于$MYPATH的文件是否存在if$MYPATH#判断位于$MYPATH的文件是否可读if$MYPATH#判断位于$MYPATH的文件是否可执行
    • Test can also determine if a variable has a value
if"$USR"#判断变量USR长度是否为零if"$USR"#判断变量USR长度是否非零
    • For compound judgment statements, the shell uses && and || to express, in particular, the shell in order to return 0 is true, 1 false, so and the operation of the && || logic is true and false, no longer the value of 0 and 1 prevail
if [ condition1 ] && [ condition2 ]if [ condition1 ] || [ condition2 ]
    • Also && can be used as a simple version of If statement, the left command returns True (that is, return 0), the right command is executed
-ne0"build rootfs Failed"return1
For statement
    • The basic usage of the For statement in the shell is that each time a loop, the variable is applied to the value of the element in the list, looping to the end of the list
#for语句假定列表元素之间以空格分割, if the element contains spaces inside it, enclose it in double quotation marks forVarinchShanghai Beijing"New York"Guangzhou DoCommands Done#for语句也可以将变量的内容作为列表值list=' Shanghai Beijing Guangzhou ' forVarinch $list   DoCommands Done#列表值的来源也可以是指令的输出, for will divide the output of the instruction with a space, and the loop ends when the output ends forVarinch' Cat$file`#此处从一个文件中读取内容, as a list value DoCommands Done
    • Now to discuss the system, which characters will the for statement use as a separator for the list elements? The default is spaces, line breaks, tab characters . We can specify the delimiter by the variable ifs, which is a very convenient mechanism
OLDIFS=$IFS    #先备份原本的IFS值IFS=$‘\n:;‘    #指定分隔符为换行符、冒号、分号#这里可以进行各种操作了IFS=$OLDIFS    #还原IFS值
    • The For statement also has a powerful use of using wildcards to get files/directories
#这里将会遍历所有满足条件的目录,并将其作为列表值,每次循环赋给变量file forin /home/root/.b* /home/root/testdo    if-d$file ].....

Shell script Programming

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.