shell脚本需要掌握的内容
主要标识符
- #!/bin/sh 或者 #!/bin/bash 表示解释此脚本的Shell程序
变量
变量命名(规则不多说了,和普通语言没有太大的差别,就是不要和关键字冲突)
使用变量,需要在变量前加 '$' 符号,为了更加有效的区分变量可以在变量的前后添加大括号'{' 和 ‘}’。比如
echo "hello $nameA",如果变量是name的话这句话就会识别为nameA为变量,所以可以修改为echo "hello ${name}A"。readonly变量
name="hello"
readonly name
- delete变量
unset name
不能删除 只读变量
字符串
单引号(用法限制很多):原样输出,变量无效;里面的单引号用转义字符也无效;
双引号(用法不同:可以用变量;可以有转义字符
不用引号(习惯使用双引号就行)
拼接字符串:不需要任何‘+’符号
字符串长度:
var="1234" echo ${#var}截取字符串:
var="0123456 echo ${var:1:3}输出为 123(从1开始截取3个字符)
数组
直接使用括号 ‘(’ ')' 表示,元素用空格分开
var_array=(value1 value2 value3)
或者使用:
var_array[0]= ; var_array[3]=; var_array[n]=;
使用 '@'或者‘’ 访问所有元素 ${var_array[*]} , ${var_array[@]}
参数的使用
参数在脚本的使用中是非常重要的内容
$# 表示参数的个数
$* 所有的参数按照 $1 $2 $3 组合起来
$$ 脚本运行的当前进程ID
$n 表示第n个参数(从1开始)
运算
算术运算
-
使用表达式 expr 来计算结果:其中要用 '
' 反引号包围,如`expr 1 + 1` `,其中数字和运算符之间要用空格隔开。支持加法
+减法-乘法\*除法\mod%相等[ $a == $b ]不相当[ $a != $b ] -
关系运算:检测两个数之间的关系
-eq等于-ne不等于-gt大于-lt小于-ge大于等于-le小于等于 -
布尔运算
!非-o或-a与 -
逻辑运算符
逻辑AND
&&逻辑OR||
浮点数运算
字符串运算
- 检测字符串是否相等
=比如 [ $a = $b ] - 检测字符串不相同
!=比如 [ $a != $b ] - 检测长度是否为0
-z为0 返回true-n非0返回true - 检查字符串s是否为空,
[ $str ]不为空返回true
文件测试运算符
方法/函数
function funname()
{
// visit the first parameter
$1
// visit the second parameter
$2
}
// call the function
funname $p1 $p2
程序逻辑
判断逻辑
- if
if condition
then
command1
command2
...
commandN
fi
- if else
if condition
then
command1
command2
...
commandN
else
command
fi
- if else if else
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
循环逻辑
- for 循环
for var in item1 itme2....
do
done
- while
while condition
do
done