天天看点

linux shell脚本编写_如何利用case语句编写shell脚本?概述需求1、脚本内容:2、执行:

概述

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
           
linux shell脚本编写_如何利用case语句编写shell脚本?概述需求1、脚本内容:2、执行:

2、执行:

[[email protected] mnt]# cat userfile user1user2user3[[email protected] mnt]# cat passfile 123456789[[email protected] mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): hello //输入错误动作Eorror![[email protected] mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): createPlease input the userfile : user //输入错误文件user is not exist [[email protected] 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.[[email protected] mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): delete //删除用户Please input the userfile : userfile[[email protected] mnt]# id user1id: user1: no such user
           
linux shell脚本编写_如何利用case语句编写shell脚本?概述需求1、脚本内容:2、执行:
linux shell脚本编写_如何利用case语句编写shell脚本?概述需求1、脚本内容:2、执行:

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

linux shell脚本编写_如何利用case语句编写shell脚本?概述需求1、脚本内容:2、执行: