bash语法
国际惯例打印hello world
1 echo "hello world"
该程序运行结果:
hello world
1.变量:
1 a=1;b="hello world";echo $a $b
该程序运行结果:
1 hello world
注意:变量赋值,“=”左右两边都不能有空格
1.1数组:
1 a=(0 1 2 3 4) 2 echo ${a[@]}
该程序运行结果:
0 1 2 3 4
1 a=({0..5}) 2 echo ${a[@]}
该程序运行结果:
0 1 2 3 4 5
1.2 字符串操作:
‘#’去掉前面部分, ‘%’去掉后面部分
s="hello world " echo "${s#*l}" echo "${s##*l}" echo "${s%l*}" echo "${s%%l*}"
该程序运行结果:
lo world
d
hello wor
he
‘/’替换字符串
a="hello world" b="${a/world/test}" echo $b
该程序运行结果:
hello haha
2 操作符:
对应的操作 | 整数操作 | 字符串操作 |
相同 | -eq | = |
不同 | -ne | != |
大于 | -gt | > |
小于 | -lt | < |
大于或等于 | -ge | |
小于或等于 | -le | |
为空 | -z | |
不为空 | -n |
文件运算符:
运算符
|
含义( 满足下面要求时返回 TRUE ) |
-e file
|
文件 file 已经存在 |
-f file
|
文件 file 是普通文件 |
-s file
|
文件 file 大小不为零 |
-d file
|
文件 file 是一个目录 |
-r file
|
文件 file 对当前用户可以读取 |
-w file
|
文件 file 对当前用户可以写入 |
-x file
|
文件 file 对当前用户可以执行 |
-g file
|
文件 file 的 GID 标志被设置 |
-u file
|
文件 file 的 UID 标志被设置 |
-O file
|
文件 file 是属于当前用户的 |
-G file
|
文件 file 的组 ID 和当前用户相同 |
file1 -nt file2
|
文件 file1 比 file2 更新 |
file1 -ot file2
|
文件 file1 比 file2 更老 |
3.控制语句
1.if...then...else....fi
1 a=1;b=2;if [ $a -lt $b ];then echo " $a < $b";else echo "false";fi
该程序运行结果:
1 < 2
2.for...do...don
方式一
1 for i in 1 2 3 4;do echo $i;done
该程序运行结果:
1
2
3
4
方式二
1 for ((i=0;i<4;i++));do echo $i;done
该程序运行结果:
0
1
2
3
4
3.
3. while...do....done
1 a=1 2 while(($a<=5)) 3 do 4 echo $a 5 ((a++)) 6 done
该程序运行结果:
1
2
3
4
5
也可以这么用,它将打印文件file里面的东西
while read x do echo $x done < file