linux shell脚本编写_如何利用case语句编写shell脚本?

概述

shell是一个命令解释器,是一个程序/bin/bash,解释linux的命令,而shell脚本是一系列的命令组成的文件,想要熟练掌握shell脚本,唯有不断练习,接触各种各样的需求并用shell来实现才可以。


需求

利用case语句编写脚本,满足下列要求

1.执行create时根据userfile和passfile建立用户

2.执行delete时根据userfile删除用户


1、脚本内容:

# vim user_ctrl.sh#!/bin/bashread -p "Please input the operation (create or delete ): " OPERATION //输入你要执行的动作case $OPERATION in create) //第一种情况:create read -p "Please input the userfile : " USERFILE //提示输入文件 [ -e $USERFILE ] || { //判断是否存在 echo "$USERFILE is not exist " exit 1 } read -p "Please input the passwdfile : " PASSFILE [ -e $PASSFILE ] || { echo "$PASSFILE is not exist " exit 1 } USERLINE=`awk 'BEGIN{N=0}{N++}END{print N}' $USERFILE` //计算userfile文件行数 for LINE_NUM in `seq 1 $USERLINE` //利用循环建立 do USERNAME=`sed -n "${LINE_NUM}p" $USERFILE` //截取userfile文件第一行内容 PASSWORD=`sed -n "${LINE_NUM}p" $PASSFILE` //截取passfile文件第一行内容 useradd $USERNAME //建立用户 echo $PASSWORD | passwd --stdin $USERNAME done ;; delete) //第二种情况:delete read -p "Please input the userfile : " USERFILE [ -e $USERFILE ] || { echo "$USERFILE is not exist " exit 1 } USERLINE=`awk 'BEGIN{N=0}{N++}END{print N}' $USERFILE` for LINE_NUM in `seq 1 $USERLINE` do USERNAME=`sed -n "${LINE_NUM}p" $USERFILE` userdel -r $USERNAME done ;; *) //第三种情况:其余各种情况 echo Error! ;;esac
903ca5e2bbe7bc6bc27155b9720a4590.png

2、执行:

[root@localhost mnt]# cat userfile user1user2user3[root@localhost mnt]# cat passfile 123456789[root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): hello //输入错误动作Eorror![root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): createPlease input the userfile : user //输入错误文件user is not exist [root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): createPlease input the userfile : userfilePlease input the passwdfile : passfile //建立用户Changing password for user user1.passwd: all authentication tokens updated successfully.Changing password for user user2.passwd: all authentication tokens updated successfully.Changing password for user user3.passwd: all authentication tokens updated successfully.[root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): delete //删除用户Please input the userfile : userfile[root@localhost mnt]# id user1id: user1: no such user
5c9ebf188cc4848e828f85b7df59f95e.png
e1a6c2375e0980308f549689111c6423.png

关于shell脚本就介绍到这了,大家在看需求的时候建议自己先写一下,然后再对着改进,效果会好一点。后面小编会分享更多linux方面内容,感兴趣的朋友走一波关注哩~

766bd009f46d89c40adcca30b8754d49.gif
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值