腳本編程部分_第十周練習
Q1:寫一個腳本:
-
(1) 能接受四個參數:start, stop, restart, status;start: 輸出“starting 腳本名 finished.”其余參數類似;
-
(2) 其它任意參數,均報錯退出;
#!/bin/bash # read -p "The following choices can be allowed.[start/stop/restart/status]" var case $var in start) echo "start $0 finished." ;; stop) echo "stop $0 finished." ;; restart) echo "restart $0 finished." ;; status) echo "status $0 finished." ;; *) echo -e "Error!\nPlease try again!" exit 1 ;; esac
Q2:寫一個腳本,判斷給定的用戶是否登錄了當前系統;
-
(1) 如果登錄了,則顯示用戶登錄,腳本終止;
-
(2) 每3秒鐘,查看一次用戶是否登錄;
#!/bin/bash # [ $# -eq 0 ] && echo -e "A username needed!\nPlease try again!" && exit 1 while true;do if id $1 &> /dev/null;then testuser=$(who | grep "^$1" | cut -d' ' -f1) if [ "$testuser" == "$1" ];then echo -e "$1 logged!\nBye~" break else echo "Please wait for a moment!" sleep 3 fi else echo -e "$1 not exits!\nPlease try again!" exit 2 fi done
Q3:寫一個腳本,顯示用戶選定要查看的信息;
-
cpu) display cpu info
-
mem) display memory info
-
disk) display disk info
-
quit) quit
-
非此四項選擇,則提示錯誤,并要求用戶重新選擇,只到其給出正確的選擇為止;
#!/bin/bash # cat << EOF cpu) display cpu info mem) display memory info disk) display disk info quit) quit ========================================== EOF read -p "Please input your option:" var while [ "$var" != "cpu" -a "$var" != "mem" -a "$var" != "disk" -a "$var" != "quit" ];do echo -e "Option Error!\ncpu, mem, disk, quit" read -p "Please input your option again:" var done case $var in cpu) lscpu ;; mem) free -m ;; disk) fdisk -l /dev/[sh]d[a-z] ;; quit) echo "Bye~" exit 0 ;; esac
Q4:寫一個腳本:
-
(1) 用函數實現返回一個用戶的UID和SHELL;用戶名通過參數傳遞而來;
-
(2) 提示用戶輸入一個用戶名或輸入“quit”退出;
-
當輸入的是用戶名,則調用函數顯示用戶信息;
-
當用戶輸入quit,則退出腳本;進一步地:顯示鍵入的用戶相關信息后,再次提醒輸出用戶名或“quit”;
#!/bin/bash # function userinfo { if id $var &> /dev/null;then idnum=$(id -u $var) shell_=$(grep "^$var" /etc/passwd | cut -d':' -f7 | cut -d"/" -f3) echo -e "$var information\nID: $idnum\nSHELL: $shell_" else echo -e "$var not exits!\nPlease try again!" fi } while true;do read -p "Username needed or COMMAND[quit]:" var if [ "$var" == "quit" ];then echo "Bye~" exit 0 else userinfo $var fi done
Q5:寫一個腳本,完成如下功能(使用函數):
-
(1) 提示用戶輸入一個可執行命令的名字;獲取此命令依賴的所有庫文件;
-
(2) 復制命令文件至/mnt/sysroot目錄下的對應的rootfs的路徑上,例如,如果復制的文件原路徑是/usr/bin/useradd,則復制到/mnt/sysroot/usr/bin/目錄中;
-
(3) 復制此命令依賴的各庫文件至/mnt/sysroot目錄下的對應的rootfs的路徑上;規則同上面命令相關的要求;
#!/bin/bash # function route_cp { if ! which --skip-alias $var &> /dev/null;then echo "$var not exits!" exit 1 else path1=$(which --skip-alias $var) [ -d /mnt/sysroot$path1 ] || mkdir -p /mnt/sysroot$path1 cp $path1 /mnt/sysroot$path1 fi } function library_cp { for lib in $(ldd `which --skip-alias $var` | grep -Eo "/lib.*[[:space:]]");do path2=$(echo "$lib" | grep -Eo "/.*/") [ -d /mnt/sysroot$path2 ] || mkdir -p /mnt/sysroot$path2 [ -f /mnt/sysroot$lib ] || cp $lib /mnt/sysroot$lib done } read -p "Input COMMAND:" var route_cp $var library_cp $var