Shell脚本和编程
概念
终端
获取用户输入、展示运算结果的硬件设备
tty
teletypeWriter的简称,和终端等价,早期指电传打印机,在Linux中是输入/输出环境
终端模拟器
Mac Terminal、ITerm2等,关联虚拟tty的输入输出软件
Shell
command interpreter,处理来自终端模拟器的输入,解释执行之后输出结果给终端
Bash
shell的一种具体表现
发展
Ken Thompson(来自贝尔实验室)在1971年为UNX开发了第一个shell,称为V6 shell
Stephen Bourne在贝尔实验室为V7UNX所开发的Bourne shell,即shell
开源组织GU为了取代Bourne shell开发的Bourne-Again shell,Bash
构成
变量
自定义变量
#变量名=变量值(等号左右不能有空格)
page size=1
page num=2
#将命令复制给变量
_1s=1s
#将命令结果赋值给变量
file list=S(1s -a)
#默认字符串,不会进行+运算
total=page size*page_num
X
#声明变量为整型
let total=page_size*page_num
declare -i total=page size*page_num
#导出环境变量
export total
declare -x total
### declare
系统环境变量
配置文件加载
运算符和引用
管道
管道与管道符,作用是将前一个命令的结果传递给后面的命令 语法:cmd1|cmd2 要求:管道右侧的命令必须能接受标准输入才行,比如grep命令,ls、mv等不能直接使用,可以使用xargs预处理 注意:管道命令仅仅处理stdout,对于stderr会予以忽略,可以使用set-o pipefail设置shell遇到管道错误退出
#!/bin/bash
cat platform.access.log | grep ERROR
netstat -an | grep ESTABLISHED |wc -1
find . -maxdepth 1 -name "*.sh" | xargs Is -1
判断命令
shell中提供了test、[、[三种判断符号,可用于:
·整数测试 ·字符串测试 ·文件测试
语法:
test condition condition [[condition ]]
注意:
- 中括号前后要有空格符;
- [和test是命令,只能使用自己支持的标志位,<、>、=只能用来比较字符串
- 中括号内的变量,最好都是用引号括起来
- [[更丰富,在整型比较中支持<、>、=,在字符串比较中支持=~正则
#!/bin/bash
#整数测试
test $n1 -eg $n2
test $n1 -lt $n2
test $nl -gt $n2
#字符串测试
test -z $str a
test -n $str a
test $str_a = $str_b
#文件测试
test -e /dmt && echo "exist"
test -f /usr/bin/npm && echo "file exist"
分支语句
语法1:
if condition; then
程序段
elif condition; then
程序段
esle
程序段
fi
语法2:
case$变量in:
"第一个变量内容")
程序段
;;
"第一个变量内容”)
程序段
;;
*)
程序段
;;
esac
#!/bin/bash
level=0
if [ -n,"$level" ]then
if [ $level == 0 ];then
prefix=ERROR
elif [ $level == 1 ];then
prefix=INFO
else
echo "log level not supported"
fi
fi
echo "[ ${prefix}] $Smessage"
循环
- while循环 while condition ; do 程序段;done
- until循环 until condition ; do程序段;done
- for循环 for var in[words...];do程序段;done
#! /bin/bash
#对列表进行循环
for foo in a b c
do
echo $foo
done
#数值方式循环
for((i=0;i<10;i++))
do
echo si
done
函数
语法一:
funcName(){echo "abc";}
语法二:
function funcName(){echo "abc";}
注意:
- shell自上而下执行,函数必须在使用前定义
- 函数获取变量和shell script类似,1、$2..获取
- 函数内return仅仅表示函数执行状态,不代表函数执行结果
- 返回结果一般使用echo、printf,在外面使用$()、‘’获取结果
- 如果没有return,函数状态是上一条命令的执行状态,存储在$?中
#!/bin/bash
printName(){
if [ $# -It 2 ] ;then
echo "illegal parameter."
exit 1
fi
echo "firstname is : $1"
echo "lastname is : $2"
}
printName jacky chen
#/bin/sh
function test(){
local word="hello world"
echo $word
return 10
unset word
}
content=test
echo"状态码:$?"
echo"执行结果:$content"
模块化
常用命令
执行
1、shell脚本一般以 .sh结尾,也可以没有,这是一个约定;第一行需要指定用什么命令解释器来执行
2、启动方式
shell展开
1.大括号展开(Brace Expansion){..} 2.波浪号展开(Tilde Expansion)~ 3.参数展开(Shell Parameter Expansion) 4.命令替换(Command Substitution) 5.数学计算(Arithmetic Expansion)$((..)) 6.文件名展开(Filename Expansion)*?[..]外壳文件名模式匹配**