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
原创文章,作者:N24_VC,如若转载,请注明出处:http://www.178linux.com/65490
评论列表(1条)
脚本写的很棒,如果可以在多加一些判断条件的话会更好,加油