shell脚本编程笔记

最近在学习shell编程,通过学习慕课课程跟着360架构师 学习Shell脚本编程,于是将课程中有的例子都敲了一遍,在此记录一下。后续还会继续写一些脚本例子玩玩。

例题1:
变量string=‘Bigdata process framework is Hadoop,Hadoop is an open source programm’,执行脚本后,打印输出string变量字符串,并给用户以下选项:
(1)打印变量长度
(2)删除字符串中所有的Hadoop
(3)替换第一个Hadoop为Mapreduce
(4)替换全部Hadoop为Mapreduce
用户输入数组1|2|3|4,可以执行对应的功能:输入q|Q则退出交互模式

#!/bin/bash

string='Bigdata process framework is Hadoop,Hadoop is an open source programm'

function print_tips()
{
    echo '====================================='
    echo "变量string=${string}"
    echo '输入1,打印变量长度'
    echo '输入2,删除字符串中所有的Hadoop'
    echo '输入3,替换第一个Hadoop为Mapreduce'
    echo '输入4,替换全部Hadoop为Mapreduce'
    echo '输入q|Q退出脚本'
    echo '====================================='
}

function print_strlen()
{
    echo "字符串长度为:${#string}"
}

function print_delete_hadoop()
{
    echo "删除字符串中所有的Hadoop,字符串为:${string//Hadoop}"
}

function print_replace_hadoop()
{
    echo "替换第一个Hadoop为Mapreduce,字符串为:${string/Hadoop/Mapreduce}"
}

function print_replace_all_hadoop()
{
    echo "替换全部Hadoop为Mapreduce,字符串为:${string//Hadoop/Mapreduce}"
}

#print_tips
#print_strlen
#print_delete_hadoop
#print_replace_hadoop
#print_replace_all_hadoop

while True
do
  print_tips
  # shellcheck disable=SC2162
  read -p '请输入指令:' input
  case $input in
  1)
    print_strlen
    ;;
  2)
    print_delete_hadoop
    ;;
  3)
    print_replace_hadoop
    ;;
  4)
    print_replace_all_hadoop
    ;;
  q|Q)
      echo '退出脚本'
    exit
    ;;
  *)
    echo '无效指令'
    ;;
  esac

done

例题2
编写一个script, 创建目录/tmp/scripts, 切换工作目录到此目录中,复制你home下的words.txt到当前目录,并重命名为test,将test里的文件及其下的目录的其他用户权限改为没有任何权限。

#!/bin/bash

echo '============================='
echo '创建目录'
mkdir /tmp/scripts

echo '=============================='
echo '切换到新建目录'
cd /tmp/scripts
directory=`pwd`
echo "当前工作目录为:${directory}"

user=`whoami`
userDirectory="/Users/${user}"
echo ${userDirectory}
echo '==============================='
echo '复制txt文化到/tmp/scripts目录'
cp "${userDirectory}/words.txt" /tmp/scripts/test.txt

echo '================================'
echo '修改文件权限'
chmod 700 /tmp/scripts/test.txt

例题3
根据系统时间获取今年还剩下多少星期,已经过了多少星期

#!/bin/bash

date=`date "+%j"`
echo "今年已经过了$(($date/7))星期"
echo "今年还剩下$(((365-$date)/7))星期"

例题4
判断nginx进程是否存在,若不存在则自动拉起该进程

#!/bin/bash

check=`ps -ef | grep nginx | grep -v color | wc -l`

if [ $check -eq 1 ];then
        `sudo nginx`
        echo 'nginx未开启,现在开启nginx'
else
        echo 'nginx已开启'
fi

例题5
提示用户输入一个正整数num,然后计算1+2+3+…+num的值,必须对num是否为正整数进行判断,不符合则让用户重新输入

#!/bin/bash

while True
do
    read -p "请输入一个正整数:" num
    expr $num + 1 &>/dev/null
    if [ $? -eq 0 ];then
        if [ $num -gt 0 ];then
          sum=0
            for((i=1;i<=num;i++))
            do
                sum=`expr $sum + $i`
            done
            echo "1+2+3+...+${num}=${sum}"
            exit
        else
            echo "输入的字符不是正整数,请重新输入"
        fi
    else
        echo "输入的字符不是正整数,请重新输入"
    fi
done

例题6

find命令用法例子

1.搜索/etc目录下的文件(非目录),文件名以conf结尾,且大于10k,然后将其删除

find /etc -type f -name '*.conf' -size +10k -exec rm -f {}

2.将/var/log目录下以log结尾的文件,且更改时间在七天以上的删除

find /var/log -name '*.log' -mtime +7 -exec rm -rf {}

3.搜索条件和例子1一样,只是不删除,而是将其复制到/root/conf目录下

find /etc -size +10k -type f -name '*.conf' -exec cp {} /root/conf

例题7.

grep命令用法例子

1.显示/proc/meminfo文件中以大小s开头的行

cat /proc/meminfo |grep -i ^"s"

2.显示/etc/passwd文件中不以/bin/bash结尾的行

cat /etc/passwd|grep -v "/bin/bash"$

3.找出/etc/passwd中的两位或三位数

cat /etc/passwd | grep -o "\<[1-9][0-9]\{1,2\}\>" | sort -nr | uniq

例题8.

sed命令用法例子

1.显示/cat/passwd文件的10-30行

sed -n '10,30p' /ect/passwd

2.显示/cat/passwd文件中包含root的行到包含shutdown的行

sed -n '/root/,/shutdown/p' /etc/passwd

3.在passwd文件开头插入hello

sed -i '1s/^/hello \n/g' passwd

4.将passwd文件的nologin替换为nologin111

sed -i 's/nologin/nologin111/g' passwd

5.删除passwd文件中包含redis的行

sed -i '/redis/d' passwd

例题9.

处理一个类似MySQL配置文件my.cnf,示例如下
编写脚本实现以下功能:输出文件有几个段,并且针对每个段可以统计配置参数总个数

如下文件配置my.cnf

[client]
#password    = your_password
port        = 3306
socket        = /tmp/mysql.sock

[mysqld]
port        = 3306
socket        = /tmp/mysql.sock
datadir = /www/server/data
default_storage_engine = InnoDB
performance_schema_max_table_instances = 400
table_definition_cache = 400
skip-external-locking
key_buffer_size = 64M
max_allowed_packet = 100G
table_open_cache = 256
sort_buffer_size = 1M
net_buffer_length = 4K
read_buffer_size = 1M
read_rnd_buffer_size = 256K
myisam_sort_buffer_size = 16M
thread_cache_size = 32
query_cache_size = 32M
tmp_table_size = 64M
sql-mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

explicit_defaults_for_timestamp = true
#skip-name-resolve
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535

log-bin=mysql-bin
binlog_format=mixed
server-id = 1
expire_logs_days = 10
slow_query_log=1
slow-query-log-file=/www/server/data/mysql-slow.log
long_query_time=3
#log_queries_not_using_indexes=on


innodb_data_home_dir = /www/server/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /www/server/data
innodb_buffer_pool_size = 256M
innodb_log_file_size = 128M
innodb_log_buffer_size = 32M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50
innodb_max_dirty_pages_pct = 90
innodb_read_io_threads = 2
innodb_write_io_threads = 2

[mysqldump]
quick
max_allowed_packet = 500M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 64M
sort_buffer_size = 1M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

预期输出结果:
1.client 2
2.mysqld 41
3.mysqldump 2
4.mysql 1
5.myisamchk 4
6.mysqlhotcopy 1

#!/bin/bash

file='my.cnf'

function get_all_paragraph()
{
    echo "`sed -n '/\[*\]/p' $file | sed -e 's/\[//g' -e 's/\]//g'`"
}

function get_paragraph_config()
{
    echo "`sed -n '/\['$1'\]/,/\[*\]/p' $file | grep -v '\[*\]' | grep -v ^'#' | grep -v ^$ | wc -l`"
}

paragraphs=`get_all_paragraph`

index=0
for item in $paragraphs
do
  index=`expr $index + 1`
  count=`get_paragraph_config $item`
  echo "$index . $item $count"
done

例题10

1.删除配置文件中的所有注释行和空行

sed -i '/^\s*$/d' *.conf && sed -i '/^[[:space:]]*#/d' *.conf

2.在配置文件中所有不以#开头的行前面添加*符号,注意:以#开头的行不添加

sed -i '/^[^#]/s/^/*&/g' passwd
sed -i '/^[^#]/i *' passwd

例题11

1.以字符串的格式打印/etc/passwd中的第7个字段,以”:”作为分隔符

awk 'BEGIN{FS=":"}{printf "%s\n",$7}' /etc/passwd | grep -v ^$

2.以10进制格式打印/etc/passwd中的第3个字段,以”:”作为分隔符

awk 'BEGIN{FS=":"}{printf "%d\n",$3}' /etc/passwd | grep -v ^$

3.匹配/etc/passwd文件中含有root字符串的所有行

awk '/root/{print $0}' /etc/passwd

4.匹配/etc/passwd文件行中以root开头的所有行

awk '/^root/{print $0}' /etc/passwd

5.使用awk计算/etc/passwd中以#开头的行数量

awk 'BEGIN{i=0}/^#/{i++}END{print i}' /etc/passwd

6.计算学生课程分数平均值,学生课程文件如下

Allen 80 90 96 98
Mike 75 84 66 78
Jerry 91 58 45 87
Bill 84 58 68 55
Li 69 59 78 63 81

awk '{printf "%s:%0.2f\n",$1,($2+$3+$4+$5)/4}' words.txt

7.计算1+2+3+4+…+100的和,请使用while,do while,for三种循环方式实现

$>>vim for.awk

BEGIN{
        sum=0
        for(i=0;i<=100;i++)
        {
                sum+=i
        }
        print sum
}

$>>awk -f for.awk
$>>vim while.awk

BEGIN{
        sum=0;
        i=1;
        while(i<=100)
        {
                sum+=i
                i++
        }
        print sum
}

$>>awk -f while.awk
$>>vim dowhile.awk

BEGIN{
        sum=0
        i=1
        do{
                sum+=i
                i++
        }while(i<=100)
        print sum
}

$>>awk -f dowhile.awk

例题12

实现一个脚本,可查看配置下进程运行情况,输出如下:

PROCESS_NAME GROUP STATUS PID CPU MEMORY START_TIME
nginx web RUNNING 59 0.0 0.0 8/26 09:10:05 2020

配置信息如下:

[service]
Web
DB
Code

[Web]
nginx
apache

[DB]
mysql

[Code]
php
python

实现代码代码如下:

#! /bin/bash

conf_name='status.conf'

#得到group列表
function get_conf_group_list() {
    group_list=`sed -n '/\[service\]/,/\[*\]/p' $conf_name | grep -v '\[*\]' | grep -v '^$'`
    echo $group_list
}

#得到一个group下的信息
function get_conf_item_list() {
    item_list=`sed -n '/\['$1'\]/,/\[*\]/p' $conf_name | grep -v '\[*\]' | grep -v '^$'`
    echo $item_list
}

#获取所有项数据
function get_all_item() {
  index=1
  for item in `get_conf_group_list`
  do
    group_item=`get_conf_item_list $item`
    for item in $group_item
    do
      echo $item
    done
  done
}
#获取服务pid
function get_service_pid() {
    service_ps=`ps -ef | grep $1 | grep -v $$ | grep -v grep | awk '{print $2}'`
    echo "$service_ps"
}

#检查服务是否开启
function check_service_is_alive() {
    check=`ps -ef | grep $1 | grep -v $$ | grep -v grep | wc -l`
    if [ $check -eq 0 ]; then
      return 1
#        echo "$1:STOPPED"
    else
      return 0
#        echo "$1:RUNNING"
    fi
}

#获取进程cpu运行情况
function get_pid_cpu(){
  pid=`ps aux | grep $1 | grep -v $$ | grep -v grep | grep $2 | awk '{print $3;exit}'`
  echo $pid
}

#获取进程内存运行情况
function get_pid_memory(){
  pid=`ps aux | grep $1 | grep -v $$ | grep -v grep | grep $2 | awk '{print $4;exit}'`
  echo $pid
}

function get_pid_lstart() {
    pid=`ps -p $1 -o lstart | grep -v STARTED | sed -e 's/三//g' -e 's/ /-/g'`
    echo $pid
}

awk 'BEGIN{printf "%-15s%-10s%-10s%-10s%-10s%-10s%-10s\n","PROCESS_NAME","GROUP","STATUS","PID","CPU","MEMORY","START_TIME"}'

for item in `get_conf_group_list`
do
  for sonItem in `get_conf_item_list $item`
  do
    check=`check_service_is_alive $sonItem`
    #停止允许
    if [ $? -eq 1 ]; then
      awk -v var1=$sonItem -v var2=$item 'BEGIN{printf "%-15s%-10s%-10s%-10s%-10s%-10s%-10s\n",var1,var2,"STOPPED","NULL","NULL","NULL","NULL"}'
    else
      for pid in `get_service_pid $sonItem`
      do
        cpu=`get_pid_cpu $sonItem $pid`
        memory=`get_pid_memory $sonItem $pid`
        lstart=`get_pid_lstart $pid`
        awk -v var1=$sonItem -v var2=$item -v var3=$pid -v var4=$cpu -v var5=$memory -v var6=$lstart 'BEGIN{printf "%-15s%-10s%-10s%-10s%-10s%-10s%-10s\n",var1,var2,"RUNNING",var3,var4,var5,var6}'
      done
    fi
  done
done
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!