shell腳本練習

寫一個腳本:
一、設定變量FILE的值爲/etc/passwd
二、依次向/etc/passwd中的每一個用戶問好,並顯示對方的shell,形如:
Hello, root, your shell: /bin/bash
三、統計一共有多少個用戶shell

#!/bin/bash
FILE="/etc/passwd"
num=`wc -l < $FILE`
echo "User count:$num"
for i in `seq 1 $num`;do
    Username=`head -$i $FILE |tail -1 | cut -d: -f1`
    Shell=`head -$i $FILE | tail -1 | cut -d: -f7`
    echo "Hello,$Username,your shell: $Shell"
done 

寫一個腳本:
一、添加10個用戶user1到user10,密碼同用戶名;統計這10個用戶的ID號之和;bash

#!/bin/bash
for i in `seq 1 10`; do
    useradd user$i
    echo "user$i" | passwd --stdin user$i
    userid=`grep "user$i" /etc/passwd | cut -d: -f3`
    sumid=$[ $sumid + $userid ]
done
echo "ID COUNT:$sumid"

寫一個腳本,分別顯示當前系統上全部默認shell爲bash的用戶和默認shell爲/sbin/nologin的用戶,並統計各種shell下的用戶總數。顯示結果形如:
BASH,3users,they are:
root,redhat,gentoo函數

NOLOGIN, 2users, they are:
bin,ftpui

#!/bin/bash
BASH_C=`grep '/bin/bash' /etc/passwd | wc -l`
NOLOGIN_C=`grep '/sbin/nologin' /etc/passwd | wc -l`
echo "BASH,$BASH_C'users',they are:"
for i in `seq 1 $BASH_C`;do
    BASH_N="$BASH_N`grep '/bin/bash' /etc/passwd | head -$i | tail -1 | cut -d: -f1`,"    
done
echo $BASH_N | sed 's/,$//'
echo "NOLOGIN,$NOLOGIN_C'users',they are:" for i in `seq 1 $NOLOGIN_C`;do NOLOGIN_N="$NOLOGIN_N`grep '/sbin/nologin' /etc/passwd | head -$i | tail -1 | cut -d: -f1`," done echo $NOLOGIN_N | sed 's/,$//'

寫一個腳本:
1) 顯示一個菜單給用戶:
d|D) show disk usages.
m|M) show memory usages.
s|S) show swap usages.
*) quit.
2) 當用戶給定選項後顯示相應的內容;
3) 當用戶選擇完成,顯示相應信息後,不退出;而讓用戶再一次選擇,再次顯示相應內容;除了用戶使用quit;spa

#!/bin/bash
#建立函數s s(){
echo '---------------------------Options------------------------------' echo 'd|D) show disk usages.' echo 'm|M) show memory usages.' echo 's|S) show swap usages.' *) quit.
#輸入一個選項參數S read
-p 'Please input your select:' S }
#調用函數s s
#建立一個while循環,只要是選項是dmsDMS,則進入case,若不是,則直接while循環結束
while [[ $S == [dmsDMS] || $S == 'quit' || $S == * ]];do case $S in [dD]) df -lh; [mM]) free -m -l | grep -v '^Swap';; [sS]) free -m -l | grep '^Swap';;
quit)
   exit;;
*)
echo '---------------------------Warning!------------------------------'
echo 'Please input your correct select,eg:[dDmMsS|quit]'
;;
esac
s done

 選項的使用code

#!/bin/bash
help(){
    echo "-m memory"
    echo "-s swap"  
    echo "-d disk space" 
    echo "-q quit"
}
help
while getopts msdqh select
do
    case $select in
    m) free -m -l | grep -v '^Swap';;
    s) free -m -l | grep '^Swap';;
    d) df -lh;;
    q) exit;;
    h)help;;
    *)
     echo "Please select help options -h ";;
    esac
done
相關文章
相關標籤/搜索