格式:
#!bin/sh #固定式
gcc 1.c -o 11#注释
./11
保存为1.sh 结尾的格式,运行之前需要为文件加上可执行权限chmod u+x 1.sh,然后加上文件路径和文件名运行文件。当前目录为:./1.sh
1,变量的定义不需要用$而且等号的两边不需要空格;
2,在unset变量时,只需要unset 变量名。不需要用$;
3,表达式求值(expr 3 + 2 echo $? || sum=$((3+2)))中expr(此时运算符的两边需要空格)和$(())是等价的(这个运算符两边不需要空格)
#!/bin/sh
expr 3 + 3 //expr a + b
echo $?
s=$((4+4))
echo $s
变量类型:在变量中如果只有数字shell解释器就会将其解释为整数,如果包含字符的话就会别解释为字符串。变量的属性可以用declare函数来限定。
初始化:变量的初始值,在变量的定义时,shell有一个默认的初始值,还有自己可以进行设置格式为${变量名:-设置的值}
eg:
#!/bin/sh
#v="123456"
echo Linux $v
echo Linux ${v:-12.34.56}
变量类型的限制:使用declare或typeset内建命令(它们是完全相同的)可以用来限定变量的属性.这是在某些编程语言中使用的定义类型不严格的方式。命令declare是bash版本2之后才有的。命令typeset也可以在ksh脚本中运行.
1)-r 只读
2)-i 整数 eg: declare -i number //脚本余下的部分会把"number"当作整数看待.
3)-a 数组
4)-f 函数
5)-x export eg:declare -x var3 //这样将声明一个变量作为脚本的环境变量而被导出。
6)-x var=$value eg:declare -x var3=373 //declare命令允许在声明变量类型的时候同时给变量赋值。
退出状态(用echo $?获得为0则表示正常反之为1-255之间的错误码)而$?是shell中的内置变量,代表着最后一次运行进程的退出状态码。
1)测试文件状态
格式一:test [参数] 文件名。格式二:[ 参数 文件名 ]
参数:-d 文件是否为目录
-s 文件是否长度大于0
-f 文件是否为普通文件
-L 文件是否为符号连接
-u 文件是否设置了suid位
-r/w/x 文件是否可读/可写/可执行
eg:test -r 1.txt
[ -r 1.txt ] //分别用echo $?返回状态值,0表示成功其他表示失败,在[]的两边分别有空格
2)测试使用逻辑操作符
-a 逻辑与 -o 逻辑或 ! 逻辑非
eg:[ -w 1.txt -a 2.txt ]//判断1.txt和2.txt是否都可写。用echo $?查看返回码
3)字符串测试
格式一:test -参数 字符串 || test 字符串1 -参数 字符串2
格式二:[ -参数 字符串 ] || [ 字符串1 -参数 字符串2 ]
参数:
= 字符串相等 != 字符串不相等 -z 字符串为空 -n 字符串不为空
eg:
test -z string
test string1 = string2
[ -n string ]
[ string1 != string2 ]
4)测试数值//实在不知道这种测试有什么意义
格式一:test "number1" 参数 "number2"
格式二:[ "number1" 参数 "number2" ]
参数;
-eq 相等
-ne 不相等
-gt 大于
-lt 小与
-le 小于等于
-ge 大于等于
eg:
test "1" -le "2"
[ "1" -ge "2"]
eg:
str1=hello world//不能有空格,会报错
str2="hello world"
str3=" str1 is $str1"
str4='str1 is $str1'
echo $str1
echo $str2
echo $str3
echo $str4
结果:
./3.sh: line 3: world: command not found
hello world
str1 is
str1 is $str1