Shell脚本练习

目录

一、Shell基础知识

1.Shell的脚本组成部分

 2.脚本的执行方式

3.脚本的退出状态码

4.一些符号

二、脚本练习

         1.在当前主机编写脚本文件history_max.sh显示主机中执行频率最高的前5个命令。

         2.判断主机是否存在rhel用户,如果存在则设置密码为redhat,如果不存在则创建用户并设置密

            码。

         3.通过设置变量HISTTIMEFORMAT,使得当执行history命令时,输出格式如下:

         4.编写一个 Shell脚本,程序执行时从键盘读入一个目录名,如果用户输入的目录不存在,则 

            提示file does not exist;如果用户输入的不是目录则提示用户必须输入目录名;如果用户输

            入的是目录则显示这个目录下所有文件的信息。

         5.写一个脚本,完成以下要求:让用户输入用户名,如果其UID为0,就显示此为管理员;否

            则,就显示其为普通用户。

         6.写一个脚本,给定一个用户,判断其UID与GID号码是否一样,如果一样,就显示此用户为

            “good guy”;否则,就显示此用户为“bad guy”。

         7.写一个脚本,给定一个文件,比如/etc/inittab,判断这个文件中是否有空白行;如果有,则

            显示其空白行数;否则,显示没有空白。


一、Shell基础知识

1.Shell的脚本组成部分

(1)第一行,指定解释器

#!/bin/bash

 (2)注释,#开头的行为注释

编辑.sh文件时自动生成关于脚本文件说明的注释

[root@localhost ~]# cat /root/.vimrc
autocmd BufNewFile *.py,*.cc,*.sh,*.java exec ":call SetTitle()"
func SetTitle()
  if expand("%:e") == 'sh'
     call setline(1,"#!/bin/bash")
     call setline(2,"#########################")
     call setline(3,"#File name:".expand("%"))
     call setline(4,"#Version:v1.0")
     call setline(5,"#Email:admin@test.com")
     call setline(6,"#Created time:".strftime("%F %T"))
     call setline(7,"#Description:")
     call setline(8,"#########################")
     call setline(9,"")
  endif
endfunc

 2.脚本的执行方式

(1)bash 脚本文件的路径:产生一个子进程

(2)脚本文件的路径:产生一个子进程(用户需要对该文件有rx权限)

(3)source 脚本文件的路径:不会产生子进程

(4). 脚本文件的路径:不会产生子进程,在当前进程运

3.脚本的退出状态码

退出状态码范围:0-255

本身命令执行后就会有一个退出状态码,可使用echo $?查看命令的退出状态码;

函数也可以返回一个退出状态码,使用return 0-255返回函数的状态码,可使用echo $?查看函数的退出状态码;

脚本执行完毕后的退出状态码取决于脚本的最后一条命令,也可以使用exit 0-255指定脚本的退出状态码,可使用echo $?查看脚本的退出状态码

4.一些符号

符号命令示例在命令行中使用的说明
` | echo \command`在反引号里面的字符会被当成shell命令执行
''echo '$var'在单引号里面的所有的特殊字符会失去特殊含义
“”echo "$var"在双引号里面除了``,\,$外所有的特殊字符会失去特殊含义
\echo "\$var"紧挨在反斜线后面的特殊字符会失去特殊含义
$echo $var读取$后面变量的值
*ls file*代表零个或多个任意字符
{}ls file{1..4} 或者ls file{1,2,3,4}匹配大括号内用逗号隔开的字符
[]grep [a-zA-Z0-9]或者[a-Z0-9] filename表示匹配方括号内的单字符
[^]grep [\^a-z] filename表示不匹配方括号内的单字符
?ls file?表示匹配任意一个字符
&&cmd1 && cmd2与,如果cmd1执行成功则执行cmd2,如果cmd1执行失败则不执行cmd2
||cmd1 || cmd2或,如果cmd1执行成功则不执行cmd2,如果cmd1执行失败则执行cmd2
!! cmd非,如果cmd执行失败,则echo $?返回零值
|cmd1 | cmd2管道符,cmd2会接收cmd1命令的输出作为他的输入
cmd1;cmd2先执行cmd1,在执行cmd2,不管命令执行成功与否,顺序执行每一条命令
>echo “test” > file重定向,可以将符号前面命令的标准输出重定向到文件file,标准错误输出到屏幕
2>ls file 2> file1将前面命令的标准错误输出重定向到文件file,标准输出输出到屏幕
&>ls file file1 &> file2将命令的标准输出和标准错误输出重定向到文件file2
>>echo “test” >> file追加重定向,可以将符号前面命令的输出追加到文件file
<mail -s "test" root < file输入重定向,从file文件读取内容作为邮件的内容
<<[root@localhost ~]# cat << eof > hello > eof当遇到eof字符时就结束编辑

二、脚本练习

1.在当前主机编写脚本文件history_max.sh显示主机中执行频率最高的前5个命令。

 步骤一:查看~/.bash_history文件内容

[root@manager ~]# cat .bash_history | more
vim /etc/ssh/sshd_config
cd /etc/yum.repos.d
ls -l
cat redhat.repo
cd /etc/yum.repos.d/
--More--

步骤二: 根据~/.bash_history文件内容特征以及题目要求,使用vim编写history_max.sh脚本

[root@manager ~]# vim history_max.sh
#!/bin/bash
#
#********************************************************************
#Author:                Shi
#Date:                  2022-12-27
#FileName:             history_max.sh
#********************************************************************
history_file=~/.bash_history
echo " count cmd"
echo "`sort $history_file | uniq -c | sort -k1 -nr | head -5`"

 eg:  sort  表示将切割出的内容排序;

           uniq -c 表示删除连续的重复行并在每列旁边显示该行连续重复出现的次数;

           sort -k1 -nr 表示指定第一列为排序依据并以数值型倒序排序。

           head -5 表示显示文件前5行

步骤三: 设置history_max.sh脚本为可执行文件

[root@manager ~]# chmod a+rx history_max.sh

 步骤四:运行验证脚本

[root@manager ~]# ./history_max.sh
 count cmd
     14 ansible node1 -i inventory -m ping
     12 vim ansible.cfg
     10 ansible node2 -i inventory -m ping
      9 vim hosts
      9 cd


2.判断主机是否存在rhel用户,如果存在则设置密码为redhat,如果不存在则创建用户并设置密码。

步骤一:使用vim编辑useradd_rhel.sh脚本

[root@manager ~]# vim useradd_rhel.sh
#!/bin/bash
#
#********************************************************************
#Author:                Shi
#Date:                  2022-12-27
#FileName:             useradd_rhel.sh
#********************************************************************

if grep rhel /etc/passwd &> /dev/null
then
  echo "user rhel already exists."
else
  useradd rhel -p redhat
  echo "add user rhel successfully."
fi

 步骤二:设置useradd_rhel.sh脚本为可执行文件

[root@manager ~]# chmod a+rx useradd_rhel.sh

 步骤三:运行验证脚本

[root@manager ~]# ./useradd_rhel.sh
enter a username: rhel
user rhel already exists.

 扩:让用户输入一个名称,检查这个用户名是否存在**,如果存在,显示该用户已经存在;如果不存在,创建这个用户,然后设置与用户的同名密码,最后提示创建成功。

[root@manager ~]# vim useradd_rhel.sh
#!/bin/bash
#
#********************************************************************
#Author:                Shi
#Date:                  2022-12-27
#FileName:             useradd_rhel.sh
#********************************************************************

read -p "enter a username: " userName

if id $userName &> /dev/null
then
        echo "user $userName already exists."
else
        useradd $userName &> /dev/null
        echo "$userName" | passwd --stdin $userName &> /dev/null
        echo "user $userName create complate,passwd is $userName"
fi
[root@manager ~]# chmod a+rx useradd_rhel.sh
[root@manager ~]# ./useradd_rhel.sh
enter a username: rhel
user rhel already exists.

[root@manager ~]# ./useradd_rhel.sh
enter a username: rhel1
user rhel1 create complate,passwd is rhel1


3.通过设置变量HISTTIMEFORMAT,使得当执行history命令时,输出格式如下:

[2022-12-25 16:53:42][root]history

步骤一: 打开 /etc/profile 或 /etc/bashrc 文件,设置环境变量HISTTIMEFORMAT

[root@manager ~]# vim /etc/profile

# /etc/profile
export HISTTIMEFORMAT="[%F %T][`whoami`]"

 步骤二:重新读取文件

[root@manager ~]# source /etc/profile

 步骤三:验证生效

[root@manager ~]# history | more
    1  [2022-12-27 15:28:53][root]vim /etc/ssh/sshd_config
    2  [2022-12-27 15:28:53][root]cd /etc/yum.repos.d
    3  [2022-12-27 15:28:53][root]ls -l
    4  [2022-12-27 15:28:53][root]cat redhat.repo
    5  [2022-12-27 15:28:53][root]cd /etc/yum.repos.d/
--More--

4.编写一个 Shell脚本,程序执行时从键盘读入一个目录名,如果用户输入的目录不存在,则提示file does not exist;如果用户输入的不是目录则提示用户必须输入目录名;如果用户输入的是目录则显示这个目录下所有文件的信息。

步骤一:使用vim编辑shell_dir.sh脚本 

[root@manager ~]# vim shell_dir.sh
#!/bin/bash
#
#********************************************************************
#Author:                Shi
#Date:                  2022-12-27
#FileName:             shell_dir.sh
#********************************************************************

read -p "please input a directory to show:" dir
[ ! -e "$dir" ] && echo "directory does not exist." && exit 1
[ ! -d "$dir" ] && echo "you must enter a directory name." && exit 2
[-d "$dir" ] && ls -l $dir

步骤二: 加可执行权限

[root@manager ~]# chmod a+rx shell_dir.sh

步骤三: 运行验证脚本

[root@manager ~]# ./shell_dir.sh
please input a directory to show:
directory dose not exist.
[root@manager ~]# ./shell_dir.sh
please input a directory to show:shell_dir.sh
you must enter a directory name.
[root@manager ~]# ./shell_dir.sh
please input a directory to show:/root
total 28
-rw-------. 1 root root 1348 Sep 24 00:58 anaconda-ks.cfg
drwxr-xr-x. 2 root root  180 Nov  4 23:50 ansible
-rw-r--r--. 1 root root 1215 Oct 26 18:53 CentOS-Stream.repo
-rwxr-xr-x. 1 root root  111 Dec 27 16:21 history_max.sh
-rw-r--r--. 1 root root 1620 Sep 24 07:38 initial-setup-ks.cfg
-rwxr-xr-x. 1 root root  206 Dec 27 17:07 ll_dir.sh
-rwxr-xr-x. 1 root root  207 Dec 27 17:11 shell_dir.sh
-rwxr-xr-x. 1 root root  269 Dec 27 16:46 useradd_rhel.sh


5.写一个脚本,完成以下要求:让用户输入用户名,如果其UID为0,就显示此为管理员;否则,就显示其为普通用户。

步骤一: 使用vim编辑user_admin.sh脚本

[root@manager ~]# vim user_admin.sh
#!/bin/bash
#
#********************************************************************
#Author:                Shi
#Date:                  2022-12-27
#FileName:             user_admin.sh
#********************************************************************
uid="`id -u $1`"
[ "$uid" -eq 0 ] && echo "user $1 is administrator." && exit 0
[[ "$uid" != 0 ]] && echo "user $1 is regular users."

 步骤二:加可执行权限

[root@manager ~]# chmod a+rx user_admin.sh

 步骤三:运行验证脚本

[root@manager ~]# ./user_admin.sh root
user root is administrator.

[root@manager ~]# ./user_admin.sh rhel
user rhel is regular users.


6.写一个脚本,给定一个用户,判断其UID与GID号码是否一样,如果一样,就显示此用户为“good guy”;否则,就显示此用户为“bad guy”。

步骤一:使用vim编辑 good_guy.sh脚本

[root@manager ~]# vim good_guy.sh
#!/bin/bash
#
#********************************************************************
#Author:                Shi
#Date:                  2022-12-27
#FileName:             good_guy.sh
#********************************************************************
uid=`id -u $1`
gid=`id -g $1`
[ "$uid" -eq "$gid" ] && echo "user $1 is good guy." && exit 0
echo "user $1 is bad guy."

 步骤二:加可执行权限

[root@manager ~]# chmod a+rx good_guy.sh

 步骤三:运行验证脚本

[root@manager ~]# id root
uid=0(root) gid=0(root) groups=0(root)
[root@manager ~]# ./good_guy.sh root
user root is good guy.


7.写一个脚本,给定一个文件,比如/etc/inittab,判断这个文件中是否有空白行;如果有,则显示其空白行数;否则,显示没有空白。

步骤一:使用vim编辑 blank_num.sh脚本

[root@manager ~]# vim blank_num.sh
#!/bin/bash
#
#********************************************************************
#Author:                Shi
#Date:                  2022-12-27
#FileName:             blank_num.sh
#********************************************************************
read -p "please input a file:" file
[ ! -e "$file" ] && echo "$file is not exist." && exit 1
[ ! -f "$file" ] && echo "the input must be a file name." && exit 2
num=`grep ^$ $file | wc -l`
[[ $num = 0 ]] && echo "this file has no blank lines." && exit
echo "this file has $num blank lines."

 步骤二:加可执行权限

[root@manager ~]# chmod a+rx blank_num.sh

步骤三:运行验证脚本

[root@manager ~]# ./blank_num.sh
please input a file:/etc/inittab
this file has no blank lines.

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值