基础Bash Shell脚本编程

在bash脚本的第一行要写上#!/bin/bash来告诉系统该脚本是bash脚本
这一行在Linux中被称为shebang
#!/bin/bash

1、变量
在bash脚本中声明变量与其他语言类似,而且不用声明变量的类型,直接赋值就可以生效,可以接受字符串、数字等变量类型
示例:
str="hello world"
上面这行代码创建了一个名为str的变量,并给它赋值为"hello world"

使用的时候在变量名前加上$进行调用
Example:
echo $str # hello world

2、数组
数组是一组数据的集合,在bash脚本中对数组的大小没有限制,
下标同样从0开始
下面示例的方法可以创建数组:
示例:
array[0] = val
array[1] = val
array[2] = val #方式一
array=([2]=val [0]=val [1]=val) #方式二
array=(val val val) #方式三
显示数组的第一个元素

${array[0]}
查看数组包含的个数

${#array[@]}
Bash 像如下示例支持三元运算操作

${varname:-word} # 如果varname存在且不为null,则返回varname的值,否则返回word
${varname:=word} # 如果varname存在且不为null,则返回varname的值,否则将word赋值给varname
${varname:+word} # 如果varname存在且不为null,则返回word的值, 否则返回null

3、字符串操作
${variable#pattern} # 如果变量内容从头开始的数据符合“pattern”,则将符合的最短数据删除
${variable##pattern} # 如果变量内容从头开始的数据符合“pattern”,则将符合的最长数据删除
${variable%pattern} # 如果变量内容从尾向前的数据符合“pattern”,则将符合的最短数据删除
${variable%%pattern} # 如果变量内容从尾向前的数据符合“pattern”,则将符合的最长数据删除
${variable/pattern/string} # 如果变量内容符合“pattern”,则第一个匹配的字符串会被string替换
${variable//pattern/string} # 如果变量内容符合“pattern”,则所有匹配的字符串会被string替换
${#varname} # 返回变量的长度

4、函数/方法
与其他语言类似,方法是一组可复用操作的集合

functname() {
shell commands
}
示例:

!/bin/bash

function hello {
echo world!
}
hello

function say {
echo $1
}
say "hello world!"
当调用hello函数时,屏幕将输出"world"

当调用say函数时,将在屏幕输出传入的第一个参数,在上例中就是"hello world!"

5、条件语句
与其他语言类似,也包含 if then else语句 和 case语句

if [ expression ]; then # [] 与 expression之间要有空格
will execute only if expression is true
else
will execute if expression is false
fi
case语句:

case expression in
pattern1 )
statements ;;
pattern2 )
statements ;;
...
esac

基本比较符:

statement1 && statement2 # statement1为true并且 statement2为true 则返回true
statement1 || statement2 # 至少一个为true,则返回true

str1=str2 # 比较两个字符串是否相等
str1!=str2 # 比较两个字符串是否不等
-n str1 # 判断str1是否为 非null
-z str1 # 判断str1是否为 null

-a file # file文件是否存在
-d file # file是否是一个文件夹
-f file # file文件是否是一个普通的非文件夹文件
-r file # 是否有可读权限
-s file # 是否存在文件并且文件内容不为空
-w file # 是否有可写权限
-x file # 是否有可执行权限
-N file # 文件是否在最后一次读取时被修改
-O file # 是否是文件的所有者
-G file # 文件的所属组是否与你属于同一组

file1 -nt file2 # file1是否比file2新 (newer than)
file1 -ot file2 # file1是否比file2旧 (older than)

-lt # 小于
-le # 小于等于
-eq # 等于
-ge # 大于等于
-gt # 大于
-ne # 不等

6、循环
支持三种循环语句. for, while , until.

for 语句:

for x := 1 to 10 do
begin
statements
end

for name [in list]
do
statements that can use $name
done

for (( initialisation ; ending condition ; update ))
do
statements...
done
while 语句:

while condition; do
statements
done
until 语句:

until condition; do
statements
done

7、调试
有几个简单的调试命令可以在bash中使用 bash命令加上 -n 参数可以不执行脚本,只检查语法错误 bash命令加上 -v 参数可以在脚本执行前把脚本内容显示出来 bash命令加上 -x 参数可以在脚本执行过程中逐步显示执行的脚本内容

bash -n scriptname
bash -v scriptname
bash -x scriptname

你可能感兴趣的:(基础Bash Shell脚本编程)