在shell脚本中的一些常用语法

echo在脚本中使用:

-ndo not output the trailing newline
-eenable interpretation of backslash escapes
-Eenable interpretation of backslash escapes
使用-e时的常见转义符:\t 、\e、\b、\a、\n    详细用法请查看帮助文档

read的使用:

       #  read -p "输出内容"  变量

 

EOF的用法:COMMAND << EOF  内容 EOF

 

变量:

          1.环境变量:$USER $UID $HOME

          2局部变量:定义在函数体内的变量只能在函数体内使用,

          3全局变量:一般在开头使用定义:declare -i  变量名=值

 

命令执行的状态返回值:使用#exit  [状态返回值]   -->可也退出当前脚本或进程wKiom1Pd3-iAQhHkAAGvBDuIZbw218.jpg

 

 

bash之选择结构 
选择程序结构用于判断给定的条件,根据判断的结果判断某些条件,根据判断的结果来控制程序的流程。(关于shell脚本中选择结构的详细使用方法请查看帮助文档)

 

判断条件的类型:

 1.字符串比较**其中需要对大于或小于使用反斜杠转义;大小根据ASCII值行进比较***wKioL1Pd4yTwqaf2AADK_GHChIY412.jpg

2.数值比较

wKioL1Pd5anDl14GAADcQGhCvmI137.jpg

3.文件比较

wKioL1Pd5EHy1hKZAAGd5CYxh10161.jpg

4.符合条件检查:命令与中括号之间有空格,中括号与连接符之间也有空格

                               [COMMAND]&&   [COMMAND]

                                [COMMAND] ||  [COMMAND]

 

对字符串进行的操作

 字符串切片: ${string:offset:length}

 取尾部的指定个数的字符:${string: -length}

 取子串:基于模式
  ${variable#*word}:删除从左侧到第一个word的所有字符
  ${variable##*word}:删除从左侧到最后的一个wod字符 
    例如:file='/var/log/messages'
                  ${file#*/}: 返回的结果是var/log/messages
                   ${file##*/}: 返回messages

  ${variable%word*}: 删除从右侧到最后一个word的所有字符

${variable%%world*}:删除从右侧到第一个word的所有字符


  例如: file='/var/log/messages'
    ${file%*/}: 返回的结果是/var/log
    ${file%%*/}: 返回结果为空

   phonenumber='010-110-8'
    ${phonenumber%%-*}
    ${phonenumber##*-}

   url="http://www.magedu.com:80"

 查找替换:
  ${variable/pattern/substi}: 替换第一次出现
  ${variable//pattern/substi}:替换所有的出现

  ${variable/#pattern/substi}:替换行首被pattern匹配到的内容
  ${variable/%pattern/substi}:    行尾

  pattern可以使用globbing中的元字符:*   ?

 查找删除:
  ${variable/pattern}  ; ${variable//pattern}  ; ${variable/#pattern}  ;${variable/%pattern}

 大小写转换:注意大小转换只能对单个字符使用
  小-->大:${variable^^}    ;大-->小:${variable,,}


变量赋值操作:

     ${parameter:-word} ; ${parameter:=word};${parameter:?word} ; ${parameter:+word}
              
     ${variable:-string} 字符串为空或未设定时返回string,否则返回字符串

     ${variable:=string  字符串为空或为设定时返回string且赋值给该变量,否则返回该变量
种结构
     (一)if  判断条件  ;then
              命令
           fi

wKioL1Pcr_ijS5cMAADIq7QkKWY808.jpg


     (二)if   判断条件 ;then
                      命令
                else
                      命令

                fi

wKioL1PcreDjAO2BAAEwnTAaKLE772.jpg           
      (三)if   判断条件 ;then
                命令
            elif   判断条件 ;then
                 命令
            ...
            else
                 命令
            fi

     if语句的多分支的使用和嵌套

          wKioL1Pcth3SfbCkAAJBJJThmmA382.jpg


case语句
        case 变量 in
        pattern1)命令 ;;
        ...
        *)命令 ;;
        esca

case的简单使用,并与if语句嵌套

wKiom1PcwAnSi5uLAAHa9ffAeg8290.jpg