case 变量 in 模式1) 命令序列1 ;; 模式2) 命令序列2 ;; 模式3) 命令序列3 ;; *) 无匹配后命令序列 esac
需求: 编写脚本,由用户输入字符串,字符串为linux则显示windows,为windows则显示Linux否则显示Other
示例: #!/bin/bash
read -p "Input string: " str case $str in windows) echo “Linux…” ;; linux) echo “Windows…” ;; *) echo “Other…” ;; esac
需求: 邀请用户输入待删除用户名。 询问用户,确定要继续删除吗 yes/no: " y 示例: #!/bin/bash #name #time #1请输入删除的用户名: read -p "please input a username : " user #2输出用户ID id $user &> /dev/null #4判断用户是否存在 if [ $? -ne 0 ];then echo “no such user: KaTeX parse error: Expected 'EOF', got '#' at position 25: … exit 1 fi #̲3请用户确认是否删除 read…action” = “y” -o “$action” = “Y” ] ;then
#else
#fi #5case写法 case “$action” in Y|y|YES|yes) userdel -r u s e r e c h o " user echo " userecho"user is deleted!" ;; *) echo “thank you” ;; esac
跳板主机 #!/usr/bin/bash #定义目标主机IP web1=192.168.122.152 web2=192.168.122.128 mysql1=192.168.122.88 #跳转菜单不退出 while : do #打印跳转菜单 cat <<EOF 1.WEB1 2.WEB2 3.MYSQL1 EOF #读取用户输入 read -p "input number: " num #判断用户选择 case n u m i n 1 ) s s h a l i c e @ num in 1) ssh alice@ numin1)sshalice@web1 ;; 2) ssh alice@$web2 ;; *) echo ‘123’ esac done 脚本美化 2 免密码登录 ssh-keygen ssh-copy-id ip地址 3 使用户登录跳板机,立即进行跳转询问。 可以将登录脚本,加进登录默认启动中。 vim ~/.bash_profile 粘贴脚本地址。 5 拒绝用户使用快捷键退出,捕捉用户信号 #!/bin/bash/ trap “” HUP INT OUIT TSTP 6 美化脚本 ±----+ | | ±----+ echo -en “\e[1;32minput number: \e[0m” read num
Command action
h 显示命令帮助 f 显示磁盘分区 d 显示磁盘挂载 m 查看内存使用 u 查看系统负载 q 退出程序 脚本: vim systemmanage.sh #!/usr/bin/bash #打印菜单 cat <<-EOF h. help f. disk partation d. filesystem mount m. memory u. system load q.exit EOF
read -p "please input [h for help]: " action case “$action” in f) fdisk -l ;; d) df -hT ;; m) free -m ;; u) uptime ;; q) exit ;; “”) ;; *) echo “error” ;; esac