Shell编程

Shell编程

1. 概述

Shell是一个命令解释器,它接收应用程序/用户命令,然后调用操作系统内核。

Shell是一个功能强大的编程语言,易编写、易调试、灵活性强。

  1. Linux提供的Shell解析器有
[root@192 ~]# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash
  1. bash 和 sh 的关系
[root@192 bin]# ll | grep bash
-rwxr-xr-x. 1 root root    964536 4月   1 2020 bash
lrwxrwxrwx. 1 root root        10 5月   8 18:21 bashbug -> bashbug-64
-rwxr-xr-x. 1 root root      6964 4月   1 2020 bashbug-64
lrwxrwxrwx. 1 root root         4 5月   8 18:21 sh -> bash
  1. Centos 默认的解析器是 bash
[root@192 bin]# echo $SHELL
/bin/bash

2. Shell 脚本入门

脚本格式

脚本以 #!/bin/bash 开头(指定解析器)

脚本示例

(1)需求:创建一个 Shell 脚本,输出 helloworld
(2)案例实操:

[root@192 scripts]# touch helloworld.sh
[root@192 scripts]# vim helloworld.sh

# 在 helloworld.sh 中输入如下内容

#!/bin/bash
echo "helloworld"

脚本的常用执行方式

第一种:采用 bash 或 sh+脚本的相对路径或绝对路径(不用赋予脚本+x 权限)

  • sh+脚本的相对路径

    [root@192 scripts]# sh ./helloworld.sh 
    helloworld
    
  • sh+脚本的绝对路径

    [root@192 scripts]# sh /scripts/helloworld.sh 
    helloworld
    
  • bash+脚本的相对路径

    [root@192 scripts]# bash ./helloworld.sh 
    helloworld
    
  • bash+脚本的绝对路径

    [root@192 scripts]# bash /scripts/helloworld.sh 
    helloworld
    

第二种:采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)

  1. 首先要赋予 helloworld.sh 脚本的+x 权限

    chmod +x helloworld.sh
    
  2. 执行脚本

    # 相对路径
    [root@192 scripts]# ./helloworld.sh 
    helloworld
    
    # 绝对路径
    [root@192 scripts]# /scripts/helloworld.sh 
    helloworld
    

注意:第一种执行方法,本质是 bash 解析器帮你执行脚本,所以脚本本身不需要执行权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。

第三种:在脚本的路径前加上"."或者 source(了解)

  1. 添加test脚本,如下:

    [root@192 scripts]# vim test.sh
    #!/bin/bash
    B=5
    
  2. 分别使用 sh,bash,./ 和 . 的方式来执行,结果如下:

    [root@192 scripts]# chmod u+x test.sh 
    [root@192 scripts]# bash test.sh 
    [root@192 scripts]# echo $B
    
    [root@192 scripts]# sh test.sh 
    [root@192 scripts]# echo $B
    
    [root@192 scripts]# ./test.sh 
    [root@192 scripts]# echo $B
    
    [root@192 scripts]# . test.sh 
    [root@192 scripts]# echo $B
    5
    

原因:

  1. 前三种方式都是在当前 shell 中打开一个子 shell 来执行脚本内容,当脚本内容结束,则子 shell 关闭,回到父 shell 中。
  2. 第四种,也就是使用在脚本路径前加“.”或者 source 的方式,可以使脚本内容在当前shell 里执行,而无需打开子 shell!这也是为什么我们每次要修改完/etc/profile 文件以后,需要 source 一下的原因。
  3. 开子 shell 与不开子 shell 的区别就在于,环境变量的继承关系,如在子 shell 中设置的当前变量,父 shell 是不可见的

3. 变量

系统预定义变量

  • 常用系统变量

    $HOME、$PWD、$SHELL、$USER

  • 案例实操

    (1)查看系统变量的值

    [root@192 scripts]# echo $HOME
    /root
    

    (2)显示当前 Shell 中所有变量:set

    [root@192 scripts]# set
    BASH=/bin/bash
    BASHOPTS=checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:histappend:hostcomplete:interactive_comments:login_shell:progcomp:promptvars:sourcepath
    BASH_ALIASES=()
    BASH_ARGC=()
    BASH_ARGV=()
    BASH_CMDS=()
    ......
    

自定义变量

  • 基本语法

    (1)定义变量:变量名=变量值,注意,=号前后不能有空格

    (2)撤销变量:unset 变量名

    (3)声明静态变量:readonly 变量,注意:不能 unset

  • 变量定义规则

    (1)变量名称可以由字母、数字和下划线组成,但是不能以数字开头,环境变量名建议大写。

    (2)等号两侧不能有空格

    (3)在 bash 中,变量默认类型都是字符串类型,无法直接进行数值运算。

    (4)变量的值如果有空格,需要使用双引号或单引号括起来。

  • 案例实操

    (1)定义变量 A

    [root@192 scripts]# A=5
    [root@192 scripts]# echo $A
    5
    

    (2)给变量 A 重新赋值

    [root@192 scripts]# A=8
    [root@192 scripts]# echo $A
    8
    

    (3)撤销变量 A

    [root@192 scripts]# unset A
    [root@192 scripts]# echo $A
    
    

    (4)声明静态的变量 B=2,不能 unset

    [root@192 scripts]# readonly B=2
    [root@192 scripts]# echo $B
    2
    [root@192 scripts]# B=9
    -bash: B: 只读变量
    

    (5)在 bash 中,变量默认类型都是字符串类型,无法直接进行数值运算

    [root@192 scripts]# c=1+2
    [root@192 scripts]# echo $c
    1+2
    

    (6)变量的值如果有空格,需要使用双引号或单引号括起来

    [root@192 scripts]# d=Hello World
    -bash: World: 未找到命令
    [root@192 scripts]# d="Hello World"
    [root@192 scripts]# echo $d
    Hello World
    

    (7) 不提升为全局环境变量时,子Shell访问不到

    [root@192 scripts]# bash # 开启进入子Shell访问B变量
    [root@192 scripts]# echo $B
    
    

    (8)可把变量提升为全局环境变量,可供其他 Shell 程序使用

    [root@192 scripts]# export B
    [root@192 scripts]# bash
    [root@192 scripts]# echo $B
    2
    

特殊变量

$n

  • 基本语法

    $n (功能描述:n 为数字,$0 代表该脚本名称,$1-$9 代表第一到第九个参数,十以上的参数,十以上的参数需要用大括号包含,如${10}

  • 案例实操

[root@192 scripts]# touch parameter.sh
[root@192 scripts]# vim parameter.sh
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2

[root@192 scripts]# chmod +x parameter.sh
[root@192 scripts]# ./parameter.sh zzz jjj

==========$n==========
./parameter.sh
zzz
jjj

$#

  • 基本语法

    $# (功能描述:获取所有输入参数个数,常用于循环,判断参数的个数是否正确以及加强脚本的健壮性)。

  • 案例实操

[root@192 scripts]# vim parameter.sh
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2
echo '==========$#=========='
echo $#
[root@192 scripts]# chmod +x parameter.sh
[root@192 scripts]# ./parameter.sh zz xx
==========$n==========
./parameter.sh
zz
xx
==========$#==========
2

¥*、¥@

  • 基本语法

    $* (功能描述:这个变量代表命令行中所有的参数,$*把所有的参数看成一个整体)

    $@(功能描述:这个变量也代表命令行中所有的参数,不过$@把每个参数区分对待)

  • 案例实操

[root@192 scripts]# vim parameter.sh
#!/bin/bash
echo '==========$n=========='
echo $0
echo $1
echo $2
echo '==========$#=========='
echo $#
echo '==========$*=========='
echo $*
echo '==========$@=========='
echo $@
[root@192 scripts]# ./parameter.sh z j h
==========$n==========
./parameter.sh
z
j
==========$#==========
3
==========$*==========
z j h
==========$@==========
z j h

$?

  • 基本语法

    $? (功能描述:最后一次执行的命令的返回状态。如果这个变量的值为 0,证明上一个命令正确执行;如果这个变量的值为非 0(具体是哪个数,由命令自己来决定),则证明上一个命令执行不正确了。)

  • 案例实操

# 判断 helloworld.sh 脚本是否正确执行

[root@192 scripts]# ./helloworld.sh
helloworld
[atguigu@hadoop101 shells]$ echo $?
0

4. 运算符

  • 基本语法
$((运算式))
或
$[运算式]
  • 案例实操:
[root@192 scripts]# S=$[(2+3)*4]
[root@192 scripts]# echo $S
20

5. 条件判断

  • 基本语法

    (1)test condition

    (2)[ condition ](注意 condition 前后要有空格)

注意:条件非空即为 true,[ test ]返回 true,[ ] 返回 false。

  • 常用判断条件

(1)两个整数之间比较

-eq 等于(equal)
-ne 不等于(not equal)
-lt 小于(less than)
-le 小于等于(less equal)
-gt 大于(greater than)
-ge 大于等于(greater equal)

注:如果是字符串之间的比较 ,用等号“=”判断相等;用“!=”判断不等。

(2)按照文件权限进行判断

-r 有读的权限(read)
-w 有写的权限(write)
-x 有执行的权限(execute)

(3)按照文件类型进行判断

-e 文件存在(existence)
-f 文件存在并且是一个常规的文件(file)
-d 文件存在并且是一个目录(directory)
  • 案例实操

(1)23 是否大于等于 22

[root@192 scripts]# [ 23 -ge 22 ]
[root@192 scripts]# echo $?
0

(2)helloworld.sh 是否具有写权限

[root@192 scripts]# [ -w helloworld.sh ]
[root@192 scripts]# echo $?
0

(3)/home/atguigu/cls.txt 目录中的文件是否存在

[root@192 scripts]# [ -e /home/atguigu/cls.txt ]
[root@192 scripts]# echo $?
1

(4)多条件判断(&& 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一条命令执行失败后,才执行下一条命令)

[root@192 scripts]# [ zjh ] && echo OK || echo notOK
OK
[root@192 scripts]# [ ] && echo OK || echo notOK
notOK

6. 流程控制(重点)

if 判断

  • 基本语法

    (1)单分支

    if [ 条件判断式 ];then
      程序
    fi
    
    或者
    
    if [ 条件判断式 ]
    then
      程序
    fi
    

    (2)多分支

    if [ 条件判断式 ]
    then
      程序
    elif [ 条件判断式 ]
    then
      程序
    else
      程序
    fi
    

注意事项:
① [ 条件判断式 ],中括号和条件判断式之间必须有空格
② if 后要有空格

  • 案例实操
[root@192 scripts]# vi if_test.sh
#!/bin/bash

if [ "$1"x = "hhh"x ]
then
        echo "welcome, hhh"
fi

# 输入第二个参数,表示年龄,判断哪个年龄段
if [ $2 -lt 18 ]
then
        echo "未成年人"
elif [ $2 -lt 35 ]
then
        echo "青年人"
elif [ $2 -lt 60 ]
then
        echo "中年人"
else
        echo "老年人"
fi

[root@192 scripts]# ./if_test.sh hhh 10
welcome, hhh
未成年人

case 语句

  • 基本语法
case $变量名 in
"值 1")
  如果变量的值等于值 1,则执行程序 1
;;
"值 2")
  如果变量的值等于值 2,则执行程序 2
;;
  …省略其他分支…
*)
  如果变量的值都不是以上的值,则执行此程序
;;
esac

注意事项:
(1)case 行尾必须为单词“in”,每一个模式匹配必须以右括号“)”结束。
(2)双分号“;;”表示命令序列结束,相当于 java 中的 break。
(3)最后的“*)”表示默认模式,相当于 java 中的 default。

  • 案例实操
[root@192 scripts]# vi case_test.sh
#!/bin/bash

case $1 in
1)
        echo "one"
;;
2)
        echo "two"
;;
3)
        echo "three"
;;
*)
        echo "number else"
;;
esac

[root@192 scripts]# ./case_test.sh 1
one

for 循环

  • 基本语法一
for (( 初始值;循环控制条件;变量变化 ))
do
  程序
done

  • 案例实操一
# 从1加到100]
[root@192 scripts]# vi for_test.sh 
#!/bin/bash

for (( i=1; i<=$1; i++ ))
do
        sum=$[ $sum + $i ]
done
echo "sum=$sum"

[root@192 scripts]# ./for_test.sh 100
sum=5050
  • 基本语法二
for 变量 in 值 1 值 2 值 3…
do
  程序
done
  • 案例实操二

(1)打印所有输入参数

[root@192 scripts]# for os in linux windows macos;do echo $os;done
linux
windows
macos

(2)比较\(*和\)@区别

$*和$@都表示传递给函数或脚本的所有参数,不被双引号""包含时,都以$1 $2 …$n的形式输出所有参数

[root@192 scripts]# vi parameter_for.sh
#!/bin/bash

echo '==========$*=========='
for para in $*
do
        echo $para
done

echo '==========$@=========='
for para in $@
do
        echo $para
done

[root@192 scripts]# ./parameter_for.sh linux windows macos
==========$*==========
linux
windows
macos
==========$@==========
linux
windows
macos

当它们被双引号""包含时,$*会将所有的参数作为一个整体,以"$1 $2 …$n"的形式输出所有参数;$@会将各个参数分开,以"$1" "$2"…"$n"的形式输出所有参数。

[root@192 scripts]# vi parameter_for.sh
#!/bin/bash

echo '==========$*=========='
for para in "$*"
do
        echo $para
done

echo '==========$@=========='
for para in "$@"
do
        echo $para
done

[root@192 scripts]# ./parameter_for.sh linux windows macos
==========$*==========
linux windows macos
==========$@==========
linux
windows
macos

while 循环

  • 基本语法
while [ 条件判断式 ]
do
  程序
done
  • 案例实操
# 从 1 加到 100
[root@192 scripts]# vi while_test.sh
#!/bin/bash

a=1
while [ $a -le $1 ]
do
        #sum=$[$sum + $a]
        #a=$[ $a + 1 ]
        let sum+=a
        let a++
done
echo $sum

[root@192 scripts]# ./while_test.sh 100
5050

read 读取控制台输入

  • 基本语法

    read (选项) (参数)

    • 选项:

      -p:指定读取值时的提示符;

      -t:指定读取值时等待的时间(秒)如果-t 不加表示一直等待

    • 参数

      变量:指定读取值的变量名

  • 案例实操
    提示 10 秒内,读取控制台输入的名称

[root@192 scripts]# vi read.sh
#!/bin/bash

read -t 10 -p "请输入您的名字:" name
echo "welcome,$name"

# 输入名称后的结果
[root@192 scripts]# ./read.sh 
请输入您的名字:zjh
welcome,zjh

# 不输入名称等待超时的结果
[root@192 scripts]# ./read.sh 
请输入您的名字:welcome,

7. 函数

系统函数

basename

  • 基本语法

    basename [string / pathname] [suffix] 功能描述:basename 命令会删掉所有的前缀包括最后一个(‘/’)字符,然后将字符串显示出来。basename 可以理解为取路径里的文件名称选项:suffix 为后缀,如果 suffix 被指定了,basename 会将 pathname 或 string 中的 suffix 去掉

  • 案例实操

[root@192 scripts]# basename /scripts/parameter.sh 
parameter.sh

# 最后的.sh就是后缀,指定的话就会去掉
[root@192 scripts]# basename /scripts/parameter.sh .sh
parameter

dirname

  • 基本语法

    dirname 文件绝对路径 (功能描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分))dirname 可以理解为取文件路径的绝对路径名称

  • 案例实操

[root@192 scripts]# dirname /scripts/parameter.sh 
/scripts

自定义函数

  • 基本语法
[ function ] funname[()]
{
  Action;
  [return int;]
}
  • 经验技巧

(1)必须在调用函数地方之前,先声明函数,shell 脚本是逐行运行。不会像其它语言一样先编译。

(2)函数返回值,只能通过$?系统变量获得,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。return 后跟数值 n(0-255)

  • 案例实操
[root@192 scripts]# vi fun_test.sh 
#!/bin/bash

function add(){
        s=$[$1 + $2]
        echo $s
}

read -p "请输入第一个整数:" a
read -p "请输入第二个整数:" b

sum=$(add $a $b)
echo "和的平方是:"$[$sum * $sum]

[root@192 scripts]# ./fun_test.sh 
请输入第一个整数:1
请输入第二个整数:2
和的平方是:9

8. 综合应用案例

需求:实现一个每天对指定目录归档备份的脚本,输入一个目录名称(末尾不带/),将目录下所有文件按天归档保存,并将归档日期附加在归档文件名上,放在/root/archive 下。这里用到了归档命令:tar后面可以加上-c 选项表示归档,加上-z 选项表示同时进行压缩,得到的文件后缀名为.tar.gz。

[root@192 scripts]# vi daily_archive.sh
#!/bin/bash

# 首先判断输入参数个数时是否为1
if [ $# -ne 1 ]
then
        echo "参数个数错误!应该输入一个参数,作为归档目录名"
        exit
fi

# 从参数中获取目录名称
if [ -d $1 ]
then
        echo
else
        echo
        echo "目录不存在!"
        echo
        exit
fi

DIR_NAME=$(basename $1)
DIR_PATH=$(cd $(dirname $1); pwd)

# 获取当前日期
DATE=$(date +%y%m%d)

# 定义生成的归档文件名称
FILE=archive_${DIR_NAME}_$DATE_.tar.gz
DEST=/root/archive/$FILE

# 开始归档目录文件
echo "开始归档..."
echo

tar -czvf $DEST $DIR_PATH/$DIR_NAME

if [ $? -eq 0 ]
then
        echo
        echo "归档成功!"
        echo "归档文件为:$DEST"
        echo
else
        echo "归档出现问题!"
        echo
fi
exit

[root@192 scripts]# ./daily_archive.sh 
参数个数错误!应该输入一个参数,作为归档目录名
[root@192 scripts]# ./daily_archive.sh 11 22
参数个数错误!应该输入一个参数,作为归档目录名
[root@192 scripts]# ./daily_archive.sh 11

目录不存在!

[root@192 scripts]# ./daily_archive.sh /scripts/

开始归档...

tar: 从成员名中删除开头的“//”
//scripts/
//scripts/hello.sh
//scripts/.hello.sh.swp
//scripts/add.sh
//scripts/if_test.sh
//scripts/for_test.sh
//scripts/parameter_for.sh
//scripts/while_test.sh
//scripts/read.sh
//scripts/cmd_test.sh
//scripts/parameter.sh
//scripts/fun_test.sh
//scripts/daily_archive.sh
//scripts/helloworld.sh
//scripts/test.sh
//scripts/case_test.sh

归档成功!
归档文件为:/root/archive/archive_scripts_.tar.gz

设置定时任务

# 查看定时任务
[root@192 scripts]# crontab -l
# 编辑定时任务(每天两点执行)
[root@192 scripts]# crontab -e
0 2 * * * /root/script/daily_archive.sh /root/scripts

# 再次查看定时任务
[root@192 scripts]# crontab -l
0 2 * * * /root/script/daily_archive.sh /root/scripts

【扩展】crontab时间参数设置

* * * * *
- - - - -
| | | | |
| | | | +---- 星期中日期值(0-7,星期日可以是0或7)
| | | +------ 月份(1-12)
| | +-------- 一个月中的日期(1-31)
| +---------- 小时(0-23)
+------------ 分钟(0-59)

# 如果你想要每天早上6点和下午3点,每小时的20分执行一次脚本
0 6,15 * * * /root/script/daily_archive.sh /root/scripts

# 如果你想要每天的8点到18点每小时的15分执行脚本
15 8-18 * * * /root/script/daily_archive.sh /root/scripts

# 如果你想要每个星期日的午夜执行脚本
0 0 * * 0 /root/script/daily_archive.sh /root/scripts

【扩展】crontab时间参数符号

# 在crontab中,我们可以使用一些特殊的字符来表示时间的参数。这些字符包括:

:表示该字段的任何可能值。例如,在分钟字段使用,表示每分钟。
/:表示频率。例如,*/10表示每十分钟。
-:表示范围。例如,1-5表示1到5点。
,:表示列表。例如,1,2,5表示1号,2号和5号。

# 每天的0点,12点和24点:
0 0,12,24 * * * /root/script/daily_archive.sh /root/scripts

#每5分钟:
*/5 * * * * /root/script/daily_archive.sh /root/scripts

# 每个工作日(周一到周五)的上午9点到下午5点,每两小时执行一次:
0 9-17/2 * * 1-5 /root/script/daily_archive.sh /root/scripts

9.正则表达式入门

正则表达式使用单个字符串来描述、匹配一系列符合某个语法规则的字符串。在很多文本编辑器里,正则表达式通常被用来检索、替换那些符合某个模式的文本。在 Linux 中,grep,sed,awk 等文本处理工具都支持通过正则表达式进行模式匹配。

常规匹配

一串不包含特殊字符的正则表达式匹配它自己,例如:

# 就会匹配所有包含 ssh 的行。
[root@192 scripts]# cat /etc/passwd | grep ssh

常用特殊字符

(1)特殊字符:^

^ 匹配一行的开头,例如:

# 就会匹配所有包含 ssh 的行。
[root@192 scripts]# cat /etc/passwd | grep ^s

(2)特殊字符:$

$ 匹配一行的结束,例如:

# 会匹配出所有以 h 结尾的行
[root@192 scripts]# cat /etc/passwd | grep h$

(3)特殊字符:.

. 匹配一个任意的字符,例如:

# 会匹配 rt, rot, root, rooot, roooot 等所有行
[root@192 scripts]# cat /etc/passwd | grep r..t

(4)特殊字符:*

* 不单独使用,他和上一个字符连用,表示匹配上一个字符 0 次或多次,例如:

# 会匹配 rt, rot, root, rooot, roooot 等所有行
[root@192 scripts]# cat /etc/passwd | grep ro*t

# 会匹配 r任意字符t 的所有行
[root@192 scripts]# cat /etc/passwd | grep r.*t

(5)字符区间(中括号):[ ]

[] 表示匹配某个范围内的一个字符,例如:

[6,8]------匹配 6 或者 8
[0-9]------匹配一个 0-9 的数字
[0-9]*------匹配任意长度的数字字符串
[a-z]------匹配一个 a-z 之间的字符
[a-z]* ------匹配任意长度的字母字符串
[a-c, e-f]-匹配 a-c 或者 e-f 之间的任意字符

# 会匹配 rt,rat, rbt, rabt, rbact,rabccbaaacbt 等等所有行
[root@192 scripts]# cat /etc/passwd | grep r[a,b,c]*t

(6)特殊字符:\

\ 表示转义,并不会单独使用。由于所有特殊字符都有其特定匹配模式,当我们想匹配某一特殊字符本身时(例如,我想找出所有包含 '$' 的行),就会碰到困难。此时我们就要将转义字符和特殊字符连用,来表示特殊字符本身,例如:

# 就会匹配所有包含 a$b 的行。注意需要使用单引号将表达式引起来。
[root@192 scripts]# cat /etc/passwd | grep ‘a\$b’

写一个手机号正则

[root@192 scripts]# echo "18012345666" | grep ^1[35789][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$
或者
# -E 将样式为延伸的正则表达式来使用
[root@192 scripts]# echo "18012345666" | grep -E ^1[35789][0-9]{9}$

10.文本处理工具

cut

cut 的工作就是“剪”,具体的说就是在文件中负责剪切数据用的。cut 命令从文件的每一行剪切字节、字符和字段并将这些字节、字符和字段输出。

  • 基本用法

    cut [选项参数] filename

    说明:默认分隔符是制表符

  • 选项参数说明

选项参数 功能
-f 列号,提取第几列
-d 分隔符,按照指定分隔符分割列,默认是制表符“\t”
-c 按字符进行切割 后加加 n 表示取第几列 比如 -c 1
  • 案例实操

(1)数据准备

[root@192 scripts]# vim cut.txt
dong shen
guan zhen
wo wo
lai lai
le le

(2)切割 cut.txt 第一列

[root@192 scripts]# cut -d " " -f 1 cut.txt 
dong
guan
wo
lai
le

(3)切割 cut.txt 第二、三列

[root@192 scripts]# cut -d " " -f 2,3 cut.txt 
shen
zhen
wo
lai
le

# 因为没有第三列所以只显示第二列

(4)在 cut.txt 文件中切割出 guan

[root@192 scripts]# cat cut.txt |grep guan | cut -d " " -f 1
guan

(5)选取系统 PATH 变量值,第 2 个“:”开始后的所有路径:

[root@192 scripts]# echo $PATH | cut -d ":" -f 3-
/usr/sbin:/usr/bin:/root/bin

(6)切割 ifconfig 后打印的 IP 地址

[root@192 scripts]# ifconfig ens33 | grep netmask | cut -d " " -f 10
192.168.236.129

awk

一个强大的文本分析工具,把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行分析处理。

  • 基本用法

    awk [选项参数] ‘/pattern1/{action1} /pattern2/{action2}...’ filename

    pattern:表示 awk 在数据中查找的内容,就是匹配模式

    action:在找到匹配内容时所执行的一系列命令

  • 选项参数说明

选项参数 功能
-F 指定输入文件分隔符
-v 赋值一个用户定义变量
  • 案例实操

(1)数据准备

[root@192 scripts]# cp /etc/passwd ./password

passwd 数据的含义
用户名:密码(加密过后的):用户 id:组 id:注释:用户家目录:shell 解析器

(2)搜索 passwd 文件以 root 关键字开头的所有行,并输出该行的第 7 列。

[root@192 scripts]# awk -F : '/^root/{print $7}' password 
/bin/bash

(3)搜索 password 文件以 root 关键字开头的所有行,并输出该行的第 1 列和第 7 列,中间以“,”号分割。

[root@192 scripts]# awk -F : '/^root/{print $1 "," $7}' password 
root,/bin/bash

注意:只有匹配了 pattern 的行才会执行 action。

(4)只显示/etc/passwd 的第一列和第七列,以逗号分割,且在所有行前面添加列名 user,start 在最后一行添加"user,end"。

[root@192 scripts]# cat /etc/passwd | awk -F : 'BEGIN{print "user, start"}{print $1 "," $7}END{print "user, end"}'
user, start
root,/bin/bash
bin,/sbin/nologin
daemon,/sbin/nologin
adm,/sbin/nologin
lp,/sbin/nologin
sync,/bin/sync
shutdown,/sbin/shutdown
halt,/sbin/halt
mail,/sbin/nologin
operator,/sbin/nologin
games,/sbin/nologin
ftp,/sbin/nologin
nobody,/sbin/nologin
systemd-network,/sbin/nologin
dbus,/sbin/nologin
polkitd,/sbin/nologin
sshd,/sbin/nologin
postfix,/sbin/nologin
chrony,/sbin/nologin
user, end

注意:BEGIN 在所有数据读取行之前执行;END 在所有数据执行之后执行。

(5)将 passwd 文件中的用户 id 增加数值 1 并输出

[root@192 scripts]# awk -v i=1 -F : '{print $3+i}' password 
  • awk 的内置变量
变量 说明
FILENAME 文件名
NR 已读的记录数(行号)
NF 浏览记录的域的个数(切割后,列的个数)
  • 案例实操

(1)统计 passwd 文件名,每行的行号,每行的列数

[root@192 scripts]# awk -F : '{print "文件名:" FILENAME "行号:" NR "列数:" NF}' password 
文件名:password行号:1列数:7
文件名:password行号:2列数:7
文件名:password行号:3列数:7
文件名:password行号:4列数:7
文件名:password行号:5列数:7
文件名:password行号:6列数:7
文件名:password行号:7列数:7
文件名:password行号:8列数:7
文件名:password行号:9列数:7
文件名:password行号:10列数:7
文件名:password行号:11列数:7
文件名:password行号:12列数:7
文件名:password行号:13列数:7
文件名:password行号:14列数:7
文件名:password行号:15列数:7
文件名:password行号:16列数:7
文件名:password行号:17列数:7
文件名:password行号:18列数:7
文件名:password行号:19列数:7

(2)查询 ifconfig 命令输出结果中的空行所在的行号

[root@192 scripts]# ifconfig | awk -F : '/^$/{print NR}'
10
19

(3)切割 IP

[root@192 scripts]# ifconfig ens33 | awk '/netmask/{print $2}'
192.168.236.129

发消息案例

可以利用 Linux 自带的 mesg 和 write 工具,向其它用户发送消息。需求:实现一个向某个用户快速发送消息的脚本,输入用户名作为第一个参数,后面直接跟要发送的消息。脚本需要检测用户是否登录在系统中、是否打开消息功能,以及当前发送消息是否为空。

# 查看是否开启消息功能(y是打开,n是关闭)
[root@192 ~]# mesg
is y

# 开启消息
[root@192 ~]# mesg y

# 关闭消息
[root@192 ~]# mesg n

# 查看当前用户信息
who am i
# 查看服务器在线用户
who
# 查看服务器开启消息的在线用户
who -T
  • 脚本如下
[root@192 ~]# vi send_msg.sh
#!/bin/bash

# 查看用户是否登录
login_user=$(who | grep -i -m 1 $1 | awk '{print $1}')

if [ -z $login_user ]
then
        echo "$1 不在线!"
        echo "脚本退出.."
        exit
fi

# 查看用户是否开通消息功能
is_allowed=$(who -T | grep -i -m 1 $1 | awk '{print $2}')

if [ $is_allowed != "+" ]
then
        echo "$1 没有开启消息功能"
        echo "脚本退出.."
        exit
fi

# 确认是否有消息发送
if [ -z $2 ]
then
        echo "没有消息发送"
        echo "脚本退出.."
        exit
fi

# 从参数中获取要发送的消息
whole_msg=$(echo $* | cut -d " " -f 2-)

# 获取用户登录的终端
user_terminal=$(who | grep -i -m 1 $1 | awk '{print $2}')

# 写入要发送的消息
echo $whole_msg | write $login_user $user_terminal

if [ $? != 0 ]
then
        echo "发送失败!"
else
        echo "发送成功!"
fi
exit

[root@192 ~]# ./send_msg.sh zjh hi,zjh
发送成功!

[zjh@192 ~]$ 
Message from root@192.168.236.129 on pts/0 at 15:57 ...
hi,zjh
EOF
posted @ 2024-05-16 11:38  橙香五花肉  阅读(0)  评论(0编辑  收藏  举报