ace_lee

数据库一年级

导航

shell学习笔记

Posted on 2017-03-15 20:14  ace_lee  阅读(174)  评论(0编辑  收藏  举报

 

\ + ENTER   换行

 

变量

shell变量无需声明即可用,默认空值

于shell,变量常量无区别,用大小写区别

所有变量视为字符串

变量赋值

 

 

Here文档

语法:

cmd << token

text(单双引号视为普通字符)

token

 

cmd <<-  _EOF_

text(单双引号视为普通字符,忽略Tab字符,可用来缩进)

_EOF_

 

函数

function name {

cmds

return

}

 

 

name() {

cmds

return

}

 

局部变量定义

local variable

 

if结构

#!/bin/bash

ANSWER=maybe

if [ -z “$ANSER” ]; then    #须有“”防止参数为空导致错误($被解读为非空)

      echo “no answer” >&2

      exit 1

fi

if [ “$ANSER” = “yes” ];then

      echo “answer is yes”

elif [ “$ANSER” = “no” ]

      echo “ answer is no”   

else

      echo “answer is maybe”

fi

exit

 

退出状态

echo $?         显示上一命令退出状态,0成功,非0失败

#true/false           系统内置命令,以0/1退出状态终止执行

 

test命令

test expression       更广泛

[ expression ]         测试命令,表达式为true,退出状态0。false非0;特殊符号< > ( )须引号或 \转义

[ [ expression ] ]  支持REG,bash独有

[ [ str=~regex ] ]  string与正则表达式regex匹配为true

[ [ str == foo.* ]] 支持模式匹配*,类似路径名扩展

(())  整数专用,无须扩展,名字识别变量--(( INT == 0 ))

文件测试

[ -e file ]              file 存在为true

[ -f file ]                   file存在且为普通文件

[ f1 -nt f2 ]          f1新于fe为true

字符串测试

[ string ] 非空为true

[ -n str ] str长度>0为true

[ -z str ]  长度=0为true

[ str1 '>'  str2 ]

整数测试

[ int1 -lt int2 ]             <

[ int1 -le int2 ]            <=

[ int1 -ne int2 ]    not =

整数regex=^-?[0-9]+$

 

控制运算符

# mkdir tem && cd tem

# [ -d dir ] | | mkdir dir

 

[ $(id –u) == 0 ]为root