tft每日頭條

 > 圖文

 > 怎麼簡單快速的寫出shell腳本

怎麼簡單快速的寫出shell腳本

圖文 更新时间:2024-08-17 11:16:45
概述

shell是一個命令解釋器,是一個程序/bin/bash,解釋linux的命令,而shell腳本是一系列的命令組成的文件,想要熟練掌握shell腳本,唯有不斷練習,接觸各種各樣的需求并用shell來實現才可以。


需求

利用case語句編寫腳本,滿足下列要求

1.執行create時根據userfile和passfile建立用戶

2.執行delete時根據userfile删除用戶


1、腳本内容:

# vim user_ctrl.sh #!/bin/bash read -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

怎麼簡單快速的寫出shell腳本(shell腳本練習--利用case語句編寫腳本)1


2、執行:

[root@localhost mnt]# cat userfile user1 user2 user3 [root@localhost mnt]# cat passfile 123 456 789 [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 ): create Please input the userfile : user //輸入錯誤文件 user is not exist [root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): create Please input the userfile : userfile Please 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 user1 id: user1: no such user

怎麼簡單快速的寫出shell腳本(shell腳本練習--利用case語句編寫腳本)2

怎麼簡單快速的寫出shell腳本(shell腳本練習--利用case語句編寫腳本)3


關于shell腳本就介紹到這了,大家在看需求的時候建議自己先寫一下,然後再對着改進,效果會好一點。後面小編會分享更多linux方面内容,感興趣的朋友走一波關注哩~

怎麼簡單快速的寫出shell腳本(shell腳本練習--利用case語句編寫腳本)4

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关圖文资讯推荐

热门圖文资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved