搜尋此網誌

Shell Script 練習範例


判斷是否為目錄,目錄內是否有資料

#!/bin/bash

if [ $# -lt 1 ] ; then
  echo "usage: $0 directories..."
  exit
fi

echo -n 'Who is this report for? '
read name


echo "\$am's Report"


for dir in "$@" ; do


  if [ -d "$dir" ] ; then
  
    if [ "$(ls -a $dir | wc -l)" -eq 2 ] ; then
      echo " $dir: is empty"
    else
      echo " $dir: is not empty"
    fi
  else
    echo " $dir: is not a directory"
  fi

done


echo "___generated for ${name}___"
exit 0




新增帳號範例

#!/bin/bash


if [ -n "$1" ] ; then
  userfile=$1
else
  userfile=user_list.txt
fi

if [ ! -f $userfile -o ! -r $userfile ] ; then
  echo "error: unable to read $userfile"
  exit 1
fi


for u in $(grep -v '^#' $userfile) ; do

  username="$(echo $u | cut -d: -f1)"
  password="$(echo $u | cut -d: -f2)"
  maxpwage="$(echo $u | cut -d: -f3)"
  supgroup="$(echo $u | cut -d: -f4)"


useradd -G $supgroup -K PASS_MAX_DAYS=$maxpwage $username
 
  echo "$password" | passwd --stdin $username

done

exit 0




配合建立使用者帳號的文字檔(user_list.txt)

# NOTE: The format of this file is as follows:
#
#       <user name>:<password>:<max password days>:<group>
#
# HINT: Make a copy of the file without this comment to use
#       with your script!
#
newuser1:Bp~j17bNu:90:client
newuser2:Vx7Kkeb1&:90:client
newuser3:&iiSx3Kt0:60:staff
newuser4:1v{3CMaig:90:staff
newuser5:jdbq6K+5K:30:client
newuser6:xK-48migP:30:staff
newuser7:2kBQu8_mh:90:staff
newuser8:@0Kd6atWi:60:client
newuser9:6B?vbqo5P:60:staff
newuser10:5tl0cBYj%:60:client
newuser11:,V1sFxw8x:90:staff
newuser12:xxWh90sO~:90:staff
newuser13:Lk;9fT9pe:90:client
newuser14:7t_EI5hxc:90:client
newuser15:{kobD36Wv:30:client
newuser16:mbA05q@Nc:30:staff
newuser17:tc7Q|tf3Y:30:staff
newuser18:mU22Wi}rb:90:client
newuser19:{j8YS0upk:90:client
newuser20:6wU5bq{Rm:90:client
newuser21:2S^7vdGzt:30:client
newuser22:jx9g,DA7u:90:client
newuser23:?Ltyl56wD:30:client
newuser24:9YglInn7{:30:client
newuser25:DJ}o50asb:60:staff



自動刪除帳號範例

#!/bin/bash

for u in $(cat username.txt)
do
    echo "Deleting $u"
       userdel -r $u
done


配合刪除使用者帳號的文字檔(username)

# NOTE: The format of this file is as follows:
#
#       <user name>:<password>:<max password days>:<group>
#
# HINT: Make a copy of the file without this comment to use
#       with your script!
#
newuser1
newuser2
newuser3
newuser4
newuser5
newuser6
newuser7
newuser8
newuser9
newuser10
newuser11
newuser12
newuser13
newuser14
newuser15
newuser16
newuser17
newuser18
newuser19
newuser20
newuser21
newuser22
newuser23
newuser24
newuser25
 

Copyright © Jackie.Chen | Powered by Blogger | Template by 54BLOGGER | Fixed by Free Blogger Templates