本文主要是shell腳本編程練習
1、寫一個腳本
(1)、獲取并列出當前系統上的所有磁盤設備;
(2)、顯示每個磁盤設備上每個分區相關的空間使用信息;
1 #!/bin/bash 2 #author:BaoZhang 3 # 4 echo " all disk and partitions are: " 5 for i in $(fdisk -l | grep -o "^/dev/sd.*" | cut -d" " -f1); 6 do 7 echo "$i" 8 df -h $i 9 echo -e "\n" 10 done
2、寫一個腳本
(1) 接受一個以上文件路徑作為參數;
(2) 顯示每個文件擁有的行數;
(3) 總結說明本次共為幾個文件統計了其行數;
1 #!/bin/bash 2 #author : BaoZhang 3 # 4 if [ $# -ne 1 ];then 5 echo "usage : file_count /path/to/somedir/" 6 exit 1 7 fi 8 cd $1 &>/dev/null 9 if [ $? -ne 0 ];then 10 echo "usage: file_count /path/to/somedir/" 11 exit 2 12 else 13 file_number=$(ls -l $1 | wc -l) 14 for i in $(ls $1); 15 do 16 echo "line number of $i is: $(cat $i | wc -l)" 17 done 18 fi 19 echo "all the file in $1 are : $file_number" 20
3、寫一個腳本
(1) 傳遞兩個以上字符串當作用戶名;
(2) 創建這些用戶;且密碼同用戶名;
(3) 總結說明共創建了幾個用戶;
1 #!/bin/bash 2 #author:BaoZhang 3 # 4 new_user=0 5 exist_user=0 6 if [ $UID -ne 0 ];then 7 echo "only root can add user" 8 exit 1 9 else 10 if [ $# -lt 2 ];then 11 echo "usage : user_add.sh username1 username2....,arguments must more then 2 username" 12 exit 2 13 else 14 for i in $*; 15 do 16 id $i &>/dev/null 17 if [ $? -eq 0 ];then 18 echo "$i exist" 19 exist_user=$[$exist_user+1] 20 echo $i | passwd --stdin $i &>/dev/null 21 echo "user $i changed the password" 22 else 23 useradd $i 24 new_user=$[$new_user+1] 25 echo $i | passwd --stdin $i &>/dev/null 26 echo "user $i add" 27 fi 28 done 29 fi 30 fi 31 echo "in the total , $new_user created, $exist_user change the password"
4、寫一個腳本,新建20個用戶,visitor1-visitor20;計算他們的ID之和;
1 #!/bin/bash 2 #author:BaoZhang 3 # 4 if [ $UID -ne 0 ];then 5 echo "only root can add user" 6 exit 1 7 else 8 for i in {1..20}; 9 do 10 id visitor$i &>/dev/null 11 if [ $? -eq 0 ];then 12 echo "visitor$i exist " 13 else 14 useradd visitor$i 15 echo "visitor$i add finished" 16 fi 17 #let sum+=$[$(cat /etc/passwd | awk -F: '{if ($1=="visitor$i") print $3}')] 18 let sum+=$[$(id -u visitor$i)] 19 done 20 fi
5、寫一腳本,分別統計/etc/rc.d/rc.sysinit、/etc/rc.d/init.d/functions和/etc/fstab文件中以#號開頭的行數之和,以及總的空白行數;
1 #!/bin/bash 2 #author:BaoZhang 3 # 4 file1=/etc/rc.d/rc.sysinit 5 file2=/etc/rc.d/init.d/functions 6 file3=/etc/fstab 7 for i in {$file1,$file2,$file3}; 8 do 9 count1+=$[$(grep "^#" $i | wc -l)] 10 count2+=$[$(grep "^[[:space:]]$" $i | wc -l)] 11 done 12 echo " start with # total line is: $count1 " 13 echo " total blank line is : $count2 "
6、寫一個腳本,顯示當前系統上所有默認shell為bash的用戶的用戶名、UID以及此類所有用戶的UID之和;
1 #!/bin/bash 2 #author:BaoZhang 3 # 4 echo "all users are :" 5 grep "/bin/bash$" /etc/passwd | cut -d: -f1,3 6 for i in $( grep "/bin/bash$" /etc/passwd | cut -d: -f1,3 | cut -d: -f2); 7 do 8 let sum+=$[$i] 9 done 10 echo "the sum of UID is: $sum"
7、寫一個腳本,顯示當前系統上所有,擁有附加組的用戶的用戶名;并說明共有多少個此類用戶;
1 #!/bin/bash 2 #author:BaoZhang 3 # 4 echo "all users are:" 5 grep "," /etc/group | cut -d: -f1 6 echo "total user count are : $(grep "," /etc/group | cut -d":" -f1 | wc -l )"
原創文章,作者:zhangbao,如若轉載,請注明出處:http://www.www58058.com/57832