shell 是什么
shell其实是一个命令解释器,它的作用是解释用户输入的命令和程序,命令和程序可以理解成我们图中的应用程序,我们linux系统中的那些命令其实也都是一个个的小程序,只不过完成的是系统的应用功能。我们在系统的终端中输入一条命令,可以立马看到一条或者几条系统回复我们的信息,其实就是shell在帮我们回复,所以shell可以称之为命令解释器。
其实在linux提供的命令行窗口执行命令和shell脚本一样,都是在执行命令,不同的是shell脚本是一次性执行很多条命令,而命令口只是敲一条,执行一条。窗口交互默认是开启别名执行的,就像ll 对应 ls -l ,而shell内是不允许的。
脚本开头
#!/bin/sh
是指定用那种解析器解析
脚本执行方式:
./相对路径文件名 需要有执行权限X
sh 绝对路径文件名 直接执行(没有权限限制)
shell脚本变量
定义 局部变量AA=6
常量(不可更改)readonly AA=6
全局变量 export AA=6
使用echo $AA
全局变量在脚本中使用时,可以直接使用,当脚本中定义全局变量时,使用用R额sourse 文件名 就可立即使用该常量,在脚本内或其他地方都可以。
$外界参数传入
./hello.sh 12 23
在脚本中就对应 $1 $2 …
特殊字符含义
$# 标识参数的个数 $* 表示所有参数,但是时参数的一个组合串
$$ 表示当前进程好 @ 与 @ 与 @与*类似但是是个数组
$? 表示上行命令执行的结果,0是没有错误,也可以在执行函数时,接收函数的返回值
当变量是字符串时,“” 自动转义 ‘’不转义
数组的定义 AA={12 23 34 45 asdf}
读取${AA[0]}
${#AA[*]} 数组长度
${#字符串} 字符串长度
计算
SUM=$(( $AA + $BB))
SUM=expr $A + $B
SUM= ( ( (( ((AA * $BB))
SUM=expr $AA / $BB
if判断
if [ $A == $B ];then
echo $A
fi
if [ $A == $B ];then
echo $A
else
echo $B
fi
if [ $A == $B ];then
echo $A
else
echo $B
fi
if [ $A == $B ] && [ $C == $D ]
then
echo $C
fi
[ -z asdf ] 判断字符串长度是否为0
[ str asd] 判断字符串是否为空
case分支判断
case $1 in
echo a
;;
echo b
;;
*))
echo
;;
for遍历
for i in $*
do
echo …
done
for循环
for (i=0;i<=89;i++)
do
echo …
done
while循环
while(i<100)
do
echo …
done
函数function
function aa(){
echo $1
}
shell脚本调用函数时,直接在调用方法后传入要传入的参数
下面给个工程实例
#!/bin/bash
SpringBoot="/root/java/spring-boot-app-1.0.0-SNAPSHOT.jar"
if [ “$1” = “” ];
then
echo -e “\033[0;31m 未输入操作名 \033[0m \033[0;34m {start|stop|restart|status} \033[0m”
exit 1
fi
if [ “$SpringBoot” = “” ];
then
echo -e “\033[0;31m 未输入应用名 \033[0m”
exit 1
fi
function start()
{
count=ps -ef |grep java|grep $SpringBoot|grep -v grep|wc -l
if [
c
o
u
n
t
!
=
0
]
;
t
h
e
n
e
c
h
o
"
count != 0 ];then echo "
count!=0];thenecho"SpringBoot is running…"
else
echo “Start $SpringBoot success…”
nohup java -server -Xms4096m -Xmx4096m -jar $SpringBoot > /dev/null 2>&1 &
fi
}
function stop()
{
echo “Stop $SpringBoot”
boot_id=ps -ef |grep java|grep $SpringBoot|grep -v grep|awk '{print $2}'
count=ps -ef |grep java|grep $SpringBoot|grep -v grep|wc -l
if [ $count != 0 ];then
kill $boot_id
count=`ps -ef |grep java|grep $SpringBoot|grep -v grep|wc -l`
boot_id=`ps -ef |grep java|grep $SpringBoot|grep -v grep|awk '{print $2}'`
kill -9 $boot_id
fi
}
function restart()
{
stop
sleep 2
start
}
function status()
{
count=ps -ef |grep java|grep $SpringBoot|grep -v grep|wc -l
if [
c
o
u
n
t
!
=
0
]
;
t
h
e
n
e
c
h
o
"
count != 0 ];then echo "
count!=0];thenecho"SpringBoot is running…"
else
echo “$SpringBoot is not running…”
fi
}
case $1 in
start)
start;;
stop)
stop;;
restart)
restart;;
status)
status;;
*)
echo -e "\033[0;31m Usage: \033[0m \033[0;34m sh $0 {start|stop|restart|status} {SpringBootJarName} \033[0m
\033[0;31m Example: \033[0m
\033[0;33m sh $0 start esmart-test.jar \033[0m"
esac