天天看點

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、執行: