SHELL脚本

Shell

shell脚本

1.shell脚本书写

  • 命名

    shell脚本最好以.sh结尾, 脚本名称做到见名知意

  • 格式

    1. 脚本开头需要使用#!指定运行环境

    2. #代表注释

    3. 脚本中不要出现中文

      样例:

      #!/bin/bash
      #Author: 脚本作者
      #Create Time: 脚本创建时间
      #Script Description: 脚本描述
      
      # 脚本代码
      
      
      

2. 运行脚本

  • 给执行权限运行脚本

    chmod u+x filename
    ./ filename
    
  • 解释器直接运行

    bash filename
    sh filename
    
    # 查看系统中的shell解释器
    cat /etc/shells
    

3. 特殊符号

~ : 家目录
! : 执行历史命令 !! 执行上一条命令 !p 执行最近一次以p开头的命令  !66 执行历史命令中第78条命令
$ : 变量取值符
+ - * / % :数学运算符
& : 后台执行
* : 通配符, 匹配所有
? : 通配符, 匹配除回车意外的一个字符
; : shell中一行可执行多条命令, 命令间用;隔开
| : 管道符, 上条命令的输出作为下条命令的输入
\ : 转义字符
``: 反引号 命令中执行命令  echo " today is `date +F%`"
'': 单引号, 表示字符串, 单引号不解释变量
"":双引号, 表示字符串

4. 管道符

上条命令的输出作为下条命令的输入

5.重定向

> :重定向输入
>> :重定向追加输入
< : 重定向输出 wc < ./test.txt 统计txt文件
<< : 重定向追加输出

6.数学运算

expr 命令: 只能做整数运算, 格式比较古板, 注意空格
[root@192 opt] expr 1 + 1
2
[root@192 opt] expr 5 \* 3
15

# 判断是否为整数, $? 表示上一条命令是否执行成功, 成功为0 失败不为0
[root@192 opt] expr 5 + 1;echo $?
6
0

let 命令:数学运算
[root@192 opt] let sum=1+1
[root@192 opt] echo $sum
2

bc 命令:小数运算
[root@192 opt] echo "scale=2;141*100/7966"|bc
1.77

7.脚本推出

exit NUM :脚本中推出命令, NUM值为0-255


exit_code.sh
#!/bin/bash

echo 'haha'
exit 0

[root@192 opt]sh exit_code.sh
haha
[root@192 opt]echo $?
0



### 
echo 'haha'
exit 10

[root@192 opt]sh exit_code.sh
haha
[root@192 opt]echo $?
10

create_script.sh

#!/usr/bin/bash
#Author:ZhangYi
#Create Time:2021-11-30 22:24
#Script Description:create shell init script

file_path=`pwd`
file_name=$1

file=$file_path/$file_name
echo "#!/usr/bin/bash" >> $file
echo "#Author:ZhangYi" >> $file
echo "#Create Time:`date`" >> $file
echo "#Script Description:" >> $file

shell交互

1. 输出-echo

语法: echo [命令选项] [字符串]

  • 命令选项

    -n :不换行
    -e :若字符串中出现以下字符, 特殊处理
    	\a: 发出警告声
    	\b: 删除前一个字符
    
  • 颜色代码

    语法:echo -e "\033[背景色;字体颜色m 字符串 \033[属性效果"

    字体颜色:30-37
    	30: 黑色
    	31: 红色
    	...
    	37:白色
    echo -e "\033[34m hhh \033[0m"
    
    字体背景色:40-47
    echo -e "\033[42;34m hhh \033[0m"
    
    属性效果:
    0m: 关闭属性效果
    1m: 设置高亮
    4m: 下划线
    5m: 闪烁
    7m: 反显
    8m: 消隐
    

2. 输入-read

语法: read [命令选项]

命令选项:
-p : 打印信息
-t : 限定时间
-s : 不回显
-n : 输入字符个数

例子:

login.sh

#!/bin/bash

echo -n "Login: "
read user_name
echo -n "Password: "
read -s -t5 -n6 pwd
echo "account:$user_name  password:$pwd"

shell 变量

  • 变量介绍

    在编程中, 我们需要一些数据临时存储再内存中以便调用

  • 变量分类

    1. 本地变量: 用户私有变量,只有本用户能使用, 保存在家目录下的.bashrc.bash_profile
    2. 全局变量:所有用户都能使用, 保存在/etc/profile/etc/bash_profile
    3. 自定义变量: 用户自定义, 脚本中的变量
  • 定义变量

    语法: 变量名=值

    在shell编程中, 变量赋值等号之间不能有空格

    变量名最好大写

    读取变量值: $变量名

    取消变量: unset 变量名

  • 定义全局变量

    1. 永久全局变量

      /etc/profile/etc/bash_profile文件中添加export 变量名=值

    2. 永久本地变量

      .bashrc.bash_profile文件中添加export 变量名=值

  • 特殊变量

    $* : 代表所有参数, 其间隔为IFS内定参数的第一个字元
    $@ : 与*类同, 不同之处不参照IFS
    $# : 参数数量
    $$ : 脚本进程号
    $_ : 最后执行的命令
    $N :shell中第N个参数
    

shell数组

  • 基本数组

    • 定义数组语法: 数组名称=(元素1 元素2 ....)

    • 数组读值: ${数组名称[索引]}

    • 数组赋值

      1. 一次赋值一个
      array[0]='tom'
      2. 一次赋值多个
      array=('tom' 'jack' 'alice')
      
    • 查看数组: declare -a

    • 访问数组元素

      echo ${array[0]} : 访问数组中第一个元素
      echo ${array[@]} : 访问数组中所有元素, 等同于echo ${array[@]}
      echo ${#array[@]} : 统计数组中元素个数
      echo ${!array[@]} : 获取所有数组元素的索引
      echo ${array[@]:1:2} : 从索引1开始, 往后获取两个值
      
  • 关联数组

    关联数组允许用户自定义索引—类似于字典结构

    声明一个关联数组

    declare -a ass_array
    ass_array[name]='tom'
    echo  ${array[name]}
    
    #2
    ass_array=([name]="tom" [age]=18)
    echo  ${array[name]}
    

流程控制语句

  • shell中五大运算

    1. 数学运算

      -eq : =
      -gt : >
      -lt : <
      -ge : >=
      -le : <=
      -ne : !=
      
    2. 字符串比较运算

      ==
      !=
      -n :检查字符串长度是否大于0
      -z :检查字符串长度是否为0
      

      例子:

      [root@docker-study ~] test $USER=="root";echo $? #$? 上一条命令的执行状态
      0
      
    3. 文件类型判断

      -d : 检查是否存在且为目录
      -f : 检查是否存在且为文件
      -e : 检查是否存在且为文件或目录
      -r : 文件是否可读
      -s : 检查文件是否存在且不为空
      -w : 文件是否可写
      -x : 文件是否可执行
      -O : 文件是否被当前用户拥有
      -G : 文件属组是否为当前用户
      
      file1 -nt file2 检查文件1是否比文件2新
      file1 -ot file2 检查文件1是否比文件2旧
      
      # 案例
      test -d /tem/abc; echo $?
      0
      
    4. 逻辑运算

      && :与
      || :或
      ! :# 案例
      if [ 条件1 ] && [ 条件2 ]
      

    IF语句

    语法:

    if [ condition ]; then
    	commands
    elif [ condition ]; then
    	commands
    else
    	commands
    fi
    

    案例:

    # 判断/tem目录下有没有abc目录, 没有就创建abc目录
    if [ ! -d /tem/abc ];then
    	mkdir /tem/abc
    	echo "create /tem/abc ok"
    fi
    

    if 高级用法:

    if (()) : 双小括号中可以做熟悉运算
    
    if ((100%3+1>10));then
    	echo 'yes'
    else
    	echo 'no'
    fi
    

FOR循环

语法:

# 语法一
for i in value1 value2 ...
	do
	commadns
done

# 案例
for i in `seq 9 -1 1`
for i in 9 8 7 6 5 4 3 2 1
	do
	echo $i
done


# 语法2
for ((变量;条件;自增减运算))
	do
	commands
done

# 案例
for (( i=3;i>0;i-- ))
	do
	echo $i
done

循环控制

sleep N : 休眠N秒
continue 
break

WHILE 循环

while [ condition ]
do
commands
done

SHELL函数

# 语法1
函数名 () {
	代码块
	return
}

# 语法2
function 函数名{
	代码块
	return
}

案例:

# func.sh
# 定于函数
start() {
	echo "service start ..."
}

function stop {
	echo " service stop ..."
}

# 函数调用
start
stop

脚本

  • nginx启动管理脚本

    #!/bin/bash
    
    # variable 变量区
    nginx_install_path=/usr/local/nginx
    nginxd=$nginx_install_path/sbin/nginx
    pid_file=$nginx_install_path/logs/nginx.pid
    
    # source function lib. 加载系统函数库
    if [ -f /etc/init.d/functions ];then
    	.  /etc/init.d/functions
    else
    	echo " not found file  /etc/init.d/functions"
    	exit 1
    fi
    
    # function 函数区
    start () {
    	if [ -f $pid_file ];then
    		nginx_pid=`cat $pid_file`
    		nginx_process_num=`ps -ef|grep $nginx_pid|grep -v 'grep'|wc -l`
    	else
    		# 两种启动nginx的方法
    		#echo "nginx start running... `daemon $nginxd`"
    		action "nginx start running..." $nginxd
    		exit 0
    	fi
    	
    	
    	if [ $nginx_process_num -ge 1 ];then
    		echo "nginx is running"
    		exit 1
    	else
    		#echo "nginx start running... `daemon $nginxd`"
    		action "nginx start running..." $nginxd
    	fi
    	
    }
    
    stop (){
    	if [ -f $pid_file ];then
    		nginx_pid=`cat $pid_file`
    		nginx_process_num=`ps -ef|grep $nginx_pid|grep -v 'grep'|wc -l`
    		if [ $nginx_process_num -ge 1 ];then
    			echo "nginx is stop"
    			$nginxd -s stop
    			exit 0
    		else
    			echo "nginx is stop"
    			exit 1
    		fi
    	else
    		nginx_process_num=`ps -ef|grep nginx|grep -v 'grep'|wc -l`
    		if [ $nginx_process_num -ge 1 ];then
    			nginx_process_id=`ps -ef|grep nginx|grep -v nginx|awk '{print $1 }'`
    			kill -9 $nginx_process_id
    			if [ $? -eq 0 ];then
    				echo "nginx is stop"
                    exit 0
                else
                	echo "nginx is stop error"
    				exit 1
    			fi
    		fi
    	fi
    }
    
    restart (){
    	stop
    	sleep 1
    	start
    }
    
    reload (){
    	if [ -f $pid_file ];then
    		nginx_pid=`cat $pid_file`
    		nginx_process_num=`ps -ef|grep $nginx_pid|grep -v 'grep'|wc -l`
    		if [ $nginx_process_num -ge 1 ];then
    			echo "nginx reload"
    			$nginx -s reload
    			exit 0
    		else
    			echo "nginx not found"
    			exit 1
    		fi
    	fi
    }
    
    status (){
    	if [ -f $pid_file ];then
    		nginx_pid=`cat $pid_file`
    		nginx_process_num=`ps -ef|grep $nginx_pid|grep -v 'grep'|wc -l`
    		if [ $nginx_process_num -ge 1 ];then
    			echo "nginx is running"
    		else
    			echo "nginx is stop"
    		fi
    	else
    		echo "nginx is stop"
    	fi
    }
    
    
    # callable
    
    case $1 in
    start) start ;;
    stop) stop ;;
    restart) restart ;;
    reload) reload ;;
    status) status ;;
    *) echo "USAGE: $0 start|stop|restart|reload|status"
    esac
    
  • 设置systemctl命令

    cp nginx.sh /etc/init.d/nginxd
    chmod 755 /etc/init.d/nginxd 
    service nginx start|stop|restart...  #使用脚本管理nginx
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值