shell笔记

本文详细介绍了Shell脚本的基础知识,包括变量定义、计算、传参、交互及复杂控制结构,如if、case、循环等。同时深入探讨了Shell函数、数组处理以及如何利用Shell脚本进行文件和文本的高效操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# $Name:         nginx_status.sh
# $Version:      v1.0
# $Function:     Nginx Status
# $Author:       lvhanzhi
# $organization: www.lvhanzhi.xyz
# $Create Date:  2016-06-23
# $Description:  Monitor Nginx Service Status
############################################################

1.shell是命令解释器
2.shell脚本=规范+语法+系统命令
3.shell脚本能做什么
    减少重复性、周期性的工作。
    减少故障的几率。
4.解释器   #!/bin/bash
    #!/bin/bash
    脚本中如果不写,在执行过程中如果./方式执行(需要权限),默认调用bash命令翻译该文件
    脚本中如果写了使用什么解释器翻译,那在使用./时则会调用对应的解释器执行
5.执行方式
    bash /tmp/test -->直接使用解释器器执行脚本,无需执行权限 
    ./test.sh -->以./运行的方式执行,需要拥有执行权限
6.变量
    变量怎么定义
        自定义 规范,命名  变量引用${} 
        系统定义
        预定义变量   $$ $# $@ $* $? 
        位置参数变量,执行脚本后面的参数,比如  /etc/init.d/network start 
    ${#变量名} 统计变量长度
    set 用来显示本地变量
    env 用来显示环境变量
    export 用来显示和设置环境变量
    unset xxx 取消变量xxx
    [root@centos7 ~]# var="hello world" #定义变量
    [root@centos7 ~]# echo $var #输出变量
    hello world
    [root@centos7 ~]# echo ${var}_aaa 
    hello world_aaa
    [root@centos7 ~]# echo "$var \$00" #转义
    hello world $00
7.传参
    [root@centos7 shell01]# vim variable.sh      [root@centos7 shell01]# bash variable.sh 1 2 3          
    #!/bin/bash                                  
    echo "#当前shell脚本的文件名: $0"           #当前shell脚本的文件名: variable.sh
    echo "#第1个shell脚本位置参数:$1"           #第1个shell脚本位置参数:1
    echo "#第2个shell脚本位置参数:$2"           #第2个shell脚本位置参数:2
    echo "#第3个shell脚本位置参数:$3"           #第3个shell脚本位置参数:3
    echo "#所有传递的位置参数是: $*"             #所有传递的位置参数是: 1 2 3
    echo "#所有传递的位置参数是: $@"             #所有传递的位置参数是: 1 2 3
    echo "#总共传递的参数个数是: $#"             #总共传递的参数个数是: 3
    echo "#当前程序运行的 PID 是: $$"            #当前程序运行的 PID 是: 22685
    echo "#上一个命令执行的返回结果: $?"         #上一个命令执行的返回结果: 0
    $*和$@的区别:加引号$*以行的形式显示,$@以列的形式显示
    $n,n为10或10以上要加{},${10}
8.计算echo "$(($(date +%Y)+1))"
    [root@centos7 shell01]# echo $(find -name "*.sh")
    ./env.sh ./variable.sh
9.交互 read -p "是否确认此操作[y/n]:" read_change
10.变量的替换
    1.从前往后删除变量内容
    [root@bgx ~]# url=www.sina.com.cn   #定义变量
    [root@bgx ~]# echo ${url}           #输出变量的值
    www.sina.com.cn
    [root@bgx ~]# echo ${url#*.}    #从前往后,最短匹配
    sina.com.cn
    [root@bgx ~]# echo ${url##*.}   #从前往后,最长匹配
    cn
    2.从后往前删除变量内容
    [root@bgx ~]# url=www.sina.com.cn   #定义变量
    [root@bgx ~]# echo ${url}           #输出变量结果
    www.sina.com.cn
    [root@bgx ~]# echo ${url%.*}        #从后往前,最短匹配
    www.sina.com
    [root@bgx ~]# echo ${url%%.*}       #从后往前,最长匹配 贪婪匹配
    www
    3.变量内容替换
    [root@m01 shell01]# echo ${url}
    www.sina.com.cn
    [root@m01 shell01]# echo ${url/n/N}
    www.siNa.com.cn
    [root@m01 shell01]# echo ${url//n/N}
    www.siNa.com.cN
11.整数运算  expr $(()) $[]   +-*/%
    expr 
        [root@centos7 ~]# n1=10
        [root@centos7 ~]# n2=20
        [root@centos7 ~]# expr $n1 + $n2
        30
        [root@centos7 ~]# expr $n1+$n2
        10+20
        [root@centos7 ~]# expr $n1 * $n2
        expr: syntax error
        [root@centos7 ~]# expr $n1 \* $n2
        200
    $(())
        [root@centos7 ~]# echo $(( $n1 \* $n2 ))
        -bash: 10 \* 20 : syntax error: invalid arithmetic operator (error token is "\* 20 ")
        [root@centos7 ~]# echo $(( $n1 * $n2 ))
        200
        [root@centos7 ~]# echo $(( $n1*$n2 ))
        200
    $[]
        [root@centos7 ~]# echo $[$n1 * $n2]
        200
        [root@centos7 ~]# echo $[$n1*$n2]
        200
        [root@centos7 ~]# echo $[$n1\*$n2]
        -bash: 10\*20: syntax error: invalid arithmetic operator (error token is "\*20")
12.小数运算bc awk
    [root@bgx shell]# yum install bc -y
    [root@bgx shell]# echo "2*4" |bc
    8
    [root@bgx shell]# echo "2^4" |bc
    16
    [root@bgx shell]# echo "scale=2;6/4" |bc    #取2位小数
    1.50
    [root@bgx shell]# awk 'BEGIN{print 1/2}'
    0.5
13.if
    if [ $1x == "ab"x ]; then
        echo "you had enter ab"
    elif [ $1x == "cd"x ]; then     
        echo "you had enter cd"
    else
        echo "you had enter unexpected word"
    fi
    -eq =、-ne !=、-gt >、-ge >=、-lt <、-le <=
    if grep 'aaa' /etc/passwd;then
        echo ok
    else
        echo error
    fi
    if文件比对方式
        参数  说明  示例
        -e  如果文件或目录存在则为真                    [ -e file ]
        -s  如果文件存在且至少有一个字符则为真           [ -s file ]
        -d  如果文件存在且为目录则为真                   [ -d file ]
        -f  如果文件存在且为普通文件则为真             [ -s file ]
        -r  如果文件存在且可读则为真                    [ -r file ]
        -w  如果文件存在且可写则为真                    [ -w file ]
        -x  如果文件存在且可执行则为真                   [ -x file ]
        if [ -e /etc/hostss ];then
        echo "ok"
        else
            echo "err"
        fi
        [ -d $dir ] && tar zcf etc.tar.gz $dir || echo "$dir目录不存在"
    if字符串比较
        参数          说明                      示例
        ==              等于则条件为真             [ "$a" == "$b" ]
        !=              不相等则条件为真            [ "$a" != "$b" ]
        -z              字符串的长度为零则为真     [ -z "$a" ]         #没有内容为真
        -n              字符串的长度不为空则为真    [ -n "$a" ]         #有内容则为真
        str1 > str2     str1大于str2为真            [ str1 > str2 ]
        str1 < str2     str1小于str2为真            [ str1 < str2 ]
    多条件判断
        -a 并且   [ 1 -lt 2 -a 2 -gt 1 ];echo $?
        -o 或者
        [[]]使用正则 ||或 &&并且,不能用-a [[ 1 -lt 2 && 2 -gt 1 ]];echo $?
        [ 1 -lt 2 ] && [ 2 -gt 1 ] 
    正则匹配
        [[ "$num" =~ ^[0-9] ]];echo $?
    小数比较
        [ 1.5 \> 2 ] && echo $? || echo $?
    判断是否为整数
        方式一:
            [root@centos7 ~]# a=1
            [root@centos7 ~]# expr $a + 1 &>/dev/null  && echo $? || echo $?
            0
            [root@centos7 ~]# a=1.1
            [root@centos7 ~]# expr $a + 1 &>/dev/null  && echo $? || echo $?
            2
            [root@centos7 ~]# a="hello world"
            [root@centos7 ~]# expr $a + 1 &>/dev/null  && echo $? || echo $?
            2
        方式二:
            if [[ $name_end =~ ^[0-9]+$ ]];then
                    echo "是整数"
            else
                    echo "不是整数"
            fi
case
    case "变量" in
        "变量1"|1)
            ;; 
        "变量2")
          ;; 
        *)
           ;;
    esac
输出颜色[ok]
    [root@centos7 scripts]# vim daemon.sh
    #!/bin/bash
    source /etc/init.d/functions
    action "true" /bin/true
    action "false" /bin/false
    [root@centos7 scripts]# sh daemon.sh 
    true                                                       [  OK  ]
    false                                                      [FAILED]

for循环:
    for ((i=1; i<=100; i++))
    do
        echo $i
    done

    for i in {1..100}
    do
        echo $i
    done

    for i `seq 1 100`
    do
        echo $i
    done
    for line in `cat all_db_name.txt`
    do
     mysqldump -uroot -p123 -B $line >/tmp/${line}.sql
    done
    #!/usr/bin/bash
    for (( a=1,b=9;a<10;a++,b-- ))
    do
        echo num is $a $b
    done

for循环自定义分隔符 IFS=$'\n'
    OLD_IFS=$IFS
    IFS=$'\n'
    for i
    do
    done
    IFS=$OLD_IFS
    for i in

let a--

进度条
    #!/bin/sh
    b=''
    for ((i=0;$i<=100;i+=2))
    do
            printf "progress:[%-50s]%d%%\r" $b $i
            sleep 0.1
            b=#$b
    done
    echo

并发 {代码} &  等待进程结束再往后执行wait
let i++
echo * #输出当前文件的所有文件
while默认按行取值
    [root@centos7 scripts]# vim a.txt
    aaa1
    aaa2
    aaa3
    [root@centos7 scripts]# vim test.sh 
    #!/bin/bash
    while read line
    do
        echo $line
    done<a.txt

continue|break|exit
    1.exit,当脚本碰到exit时,直接退出,剩余不管有多少代码都不执行。
    2.break,结束当前循环,但会执行循环之后的所有的代码。
    3.continue 忽略本次循环剩余的所有代码,直接进行下一次循环,直到循环结束,然后继续循环之后的代码。
#!/usr/bin/expect
    #!/usr/bin/expect 
    spawn /usr/bin/ssh root@192.168.1.1
    expect "*password:" 
    send "123456\r" 
    expect "*]#" 
    send "ifconfig\r" 
    expect "*]#" 
    send "exit\r" 
    expect eof
数组
    list=(linux shell nginx test)
    echo ${list[2]}
    echo ${list[*]}
    echo ${list[@]}
    echo ${!list[*]}  #输出全部的下标
    echo ${#list[*]}  #统计个数
    unset list  #删除变量
    list[0]="root"
    list=(1 2 3 [10]=10)
    declare -A dic  #申明关联数组
    dic=([name]=lhz [age]=18)
    declare -a #查看普通数组
    declare -A #查看关联数组
数组统计
    #!/usr/bin/bash
    declare -A info_sex
    while read line
    do
        type=$(echo $line|awk -F "/" '{print $NF}')
        let info_sex[$type]++
    done</etc/passwd
    for i in ${!info_sex[@]}
    do
        echo 索引的名称:$i 索引对应次数: ${info_sex[$i]}
    done
函数
    函数名(){}
    function 函数名 { $1 $* } #$*会一次性再输出全部的
        函数名 a b c
    rc=$(函数名 a b c)
    echo $rc #输出 a b c
    return只能返回1-255的整数
        #!/bin/bash
        game(){
            if [ $1 -gt 0 -a $1 -lt 10 ];then
                return 0
            else 
                return 3
            fi
        }
        game $1
        echo $?


用shell处理以下内容
1、按单词出现频率降序排序!
2、按字母出现频率降序排序!
the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation

#方法一:sort排序-->单词
[root@oldboyedu shell08]# echo "the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation"|sed 's#[.,]# #g'|xargs -n1|sort |uniq -c |sort -nr

#方法一:sort排序-->字母
[root@oldboyedu shell08]# echo "the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation"|sed 's#[.,]# #g'|grep -o '[a-Z]'|sort |uniq -c|sort -nr


#方法二:awk排序-->字母
[root@oldboyedu shell08]#  echo "the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation"|grep -o '[a-Z]'|awk '{code[$1]++} END { for (i in code) print code[i],i}'|sort -nr

#方法二:awk排序-->单词
[root@oldboyedu shell08]#  echo "the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation"|sed 's#[.,]# #g'|xargs -n1|awk '{code[$1]++} END { for (i in code) print code[i],i}'|sort -nr


#方法三:shell数组排序-->字母
[root@oldboyedu shell08]#  cat 09.sh 
#!/usr/bin/bash
declare -A array_txt

txt="the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation"
txt=$(echo $txt |sed 's#[.,]# #g')

for i in $txt
do
    let array_txt[$i]++
done

    #2.遍历数组
for j in ${!array_txt[@]}
do
    echo 次数是: "${array_txt[$j]}" "索引$j"
done

#方法三:awk排序-->单词
[root@oldboyedu shell08]# cat 10.sh 
#!/usr/bin/bash
declare -A array_txt

te (){
txt="the squid project provides a number of resources toassist users design,implement and support squid installations. Please browsethe documentation and support sections for more infomation"
txt=$(echo $txt |grep -o "[a-Z]")

for i in $txt
do
    let array_txt[$i]++
done

#2.遍历数组
for j in ${!array_txt[@]}
do
    echo 次数是: "${array_txt[$j]}" "索引$j"
done
}

te |sort -t ":" -k 2 -nr

转载于:https://www.cnblogs.com/lvhanzhi/p/10749049.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值