if语句和case语句用法展示
SHELL脚本编程条件选择(if语句)和条件判断(case语句)
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
[root@node101.yinzhengjie.org.cn ~]# help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Execute commands based on conditional. The `if COMMANDS' list is executed. If its exit status is zero, then the
`then COMMANDS' list is executed. Otherwise, each `elif COMMANDS' list is
executed in turn, and if its exit status is zero, the corresponding
`then COMMANDS' list is executed and the if command completes. Otherwise,
the `else COMMANDS' list is executed, if present. The exit status of the
entire construct is the exit status of the last command executed, or zero
if no condition tested true. Exit Status:
Returns the status of the last command executed.
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# help if #查看if语句的帮助信息
语法格式一(推荐)
if [ 条件测试表达式 ];then
源代码
fi 语法格式二
if [ 条件测试表达式 ]
then
源代码
fi 温馨提示:
条件选择语句顾名思义就是根据条件测试表达式是否为true选择执行。
if语句可嵌套。
if语句使用fi结尾,和一般语言使用大括号结尾不同;
[ 条件测试表达式 ]就是使用test命令测试,所以中括号和条件判断式之间必须有空格;
then后面跟符合条件之后执行的程序,可以放在[]之后,用";"分割。也可以换行写入,就不需要";"啦;
[root@node101.yinzhengjie.org.cn ~]# vim shell/partitions.sh #编写一个监控boot分区的脚本
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/partitions.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/partitions.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** res=$(df -h | grep "/dev/sda1" | awk '{print $5}'| cut -d "%" -f1) if [ $res -ge ]
then
echo "Warning! /dev/sda2 is full!!!"
fi
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# chmod +x shell/partitions.sh
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ll shell/partitions.sh
-rwxr-xr-x root root Nov : shell/partitions.sh
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/centos-root 50G .5G 49G % /
devtmpfs .9G .9G % /dev
tmpfs .9G .9G % /dev/shm
tmpfs .9G 8.6M .9G % /run
tmpfs .9G .9G % /sys/fs/cgroup
/dev/sda1 1014M 146M 869M % /boot
/dev/mapper/centos-home 941G .0G 938G % /home
tmpfs 783M 783M % /run/user/
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ./shell/partitions.sh
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# dd if=/dev/zero of=/boot/bigfile bs=1M count= #为了达到测试效果,为我们可以把在"/boot"分区里写入一个大文件从而达到快速达到脚本报警阈值。
+ records in
+ records out
bytes ( MB) copied, 1.78826 s, MB/s
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/centos-root 50G .5G 49G % /
devtmpfs .9G .9G % /dev
tmpfs .9G .9G % /dev/shm
tmpfs .9G 8.6M .9G % /run
tmpfs .9G .9G % /sys/fs/cgroup
/dev/sda1 1014M 948M 67M % /boot
/dev/mapper/centos-home 941G .0G 938G % /home
tmpfs 783M 783M % /run/user/
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ./shell/partitions.sh
Warning! /dev/sda2 is full!!!
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/partitions.sh #编写一个监控boot分区的脚本
[root@node101.yinzhengjie.org.cn ~]# declare -f | grep if #不难发现系统中定义的脚本也有很多if嵌套使用案例
if [[ ${!} == \~* ]]; then
if [[ ${!} == */* ]]; then
if [[ $index -gt 0 && ( -n $lead && -n ${lead//[[:space:]]} ) ]]; then
if [[ $i -lt $cword ]]; then
if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then
if [[ $option =~ (\[((no|dont)-?)\]). ]]; then
if [[ -n $1 ]]; then
if [[ -n $exclude ]]; then
if _complete_as_root; then
if _complete_as_root; then
if [[ ${1:-} == -w ]]; then
if [[ ${1:-} == -a ]]; then
cmd="{ ifconfig || ip link show up; }";
cmd="{ ifconfig -a || ip link show; }";
COMPREPLY=($( eval $cmd 2>/dev/null | awk '/^[^ \t]/ { if ($1 ~ /^[0-9]+:/) { print $2 } else { prin
t $1 } }' )); if [[ -z "${CDPATH:-}" || "$cur" == ?(.)?(.)/* ]]; then
if [[ ( -n $mark_symdirs && -h $j || -n $mark_dirs && ! -h $j ) && ! -d ${j#$i/} ]]; then
if [[ ${#COMPREPLY[@]} -eq 1 ]]; then
if [[ "$i" == "$cur" && $i != "*/" ]]; then
if [[ "${COMP_WORDS[i]}" != -* ]]; then
if [[ $COMP_CWORD -eq ]]; then
if [[ ! -n $cspec && $cmd == */* ]]; then
if [[ ! -n $cspec ]]; then
if [[ -n $cspec ]]; then
if [[ ${cspec#* -F } != $cspec ]]; then
if [[ ${#COMP_WORDS[@]} -ge 2 ]]; then
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
if [[ -f /etc/debian_version ]]; then
COMPREPLY=($( compgen -W "$( sed -ne 's|^iface \([^ ]\{1,\}\).*$|\1|p' /etc/network/interface
s )" -- "$cur" )); if [[ -f /etc/SuSE-release ]]; then
COMPREPLY=($( compgen -W "$( printf '%s\n' /etc/sysconfig/network/ifcfg-* |
sed -ne 's|.*ifcfg-\(.*\)|\1|p' )" -- "$cur" )); if [[ -f /etc/pld-release ]]; then
COMPREPLY=($( compgen -W "$( command ls -B /etc/sysconfig/interfaces | s
ed -ne 's|.*ifcfg-\(.*\)|\1|p' )" -- "$cur" )); COMPREPLY=($( compgen -W "$( printf '%s\n' /etc/sysconfig/network-scripts/ifcfg-* |
sed -ne 's|.*ifcfg-\(.*\)|\1|p' )" -- "$cur" )); if [[ "$cur" == \~*/* ]]; then
if [[ "$cur" == \~* ]]; then
if [[ "$1" != -d ]]; then
if [[ ${#toks[@]} -ne ]]; then
if [[ $xspec == !* ]]; then
if [[ ${#toks[@]} -ne ]]; then
if [[ -e /proc/filesystems ]]; then
if [[ -n ${//[^0-9]/} ]]; then
if [[ "${#words[cword]}" -eq || "$COMP_POINT" == "${#COMP_LINE}" ]]; then
if [[ "$i" -lt "$cword" ]]; then
if [[ "${words[cword]:0:${#cur}}" != "$cur" ]]; then
if [[ "${COMP_WORDS[i]}" != -* ]]; then
if [[ $COMP_CWORD -ge ]]; then
if type getent &>/dev/null; then
if type perl &>/dev/null; then
if [[ $cur == $redir* || $prev == $redir ]]; then
if [[ ${words[i]} == $redir* ]]; then
COMPREPLY=($( compgen -W "$( PATH="$PATH:/sbin" lsmod | awk '{if (NR != 1) print $1}' )" -- "$1" ))
COMPREPLY+=($( compgen -W "$( { LC_ALL=C ifconfig -a || ip addr show; } 2>/dev/null |
[[ $# -ge $OPTIND ]] && echo "error: $FUNCNAME("$@"): unprocessed arguments:" $(while [[ $# -ge $OPTIND ]];
do printf '%s\n' ${!OPTIND}; shift; done); if [[ -n $configfile ]]; then
if [[ ${#config[@]} -gt ]]; then
if [[ -z $configfile ]]; then
if [[ ${#kh[@]} -gt || ${#khd[@]} -gt ]]; then
if [[ "$awkcur" == [-]*[.:]* ]]; then
if [[ "$awkcur" == [-]* ]]; then
if [[ -z $awkcur ]]; then
if [[ ${#kh[@]} -gt ]]; then
if ($i !~ /[*?]/ && $i ~ /'"$awkcur"'/) {print $i} \
if [[ ${#khd[@]} -gt ]]; then
if [[ "$i" == *key_22_$curd*.pub && -r "$i" ]]; then
if [[ ${#config[@]} -gt && -n "$aliases" ]]; then
if [[ -n ${COMP_KNOWN_HOSTS_WITH_AVAHI:-} ]] && type avahi-browse &>/dev/null; then
if [[ -n ${COMP_KNOWN_HOSTS_WITH_HOSTFILE-} ]]; then
if [[ "$cur" == -* ]]; then
if [[ "$1" == @(mk|rm)dir ]]; then
COMPREPLY+=($( { ifconfig -a || ip link show; } >/dev/null | sed -ne "s/.*[[:space:]]HWaddr[[:space
:]]\{,\}\($re\)[[:space:]].*/\/p" -ne "s/.*[[:space:]]HWaddr[[:space:]]\{,\}\($re\)[[:space:]]*$/\/p" -ne "s|.*[[:space:]]\(link/\)\{,\}ether[[:space:]]\{,\}\($re\)[[:space:]].*|\|p" -ne "s|.*[[:space:]]\(link/\)\{,\}ether[[:space:]]\{,\}\($re\)[[:space:]]*$|\|p" if [[ $1 == \'* ]]; then
if type -p realpath > /dev/null; then
if type -p greadlink > /dev/null; then
if type -p readlink > /dev/null; then
if [[ $cword -eq && $prev == ?(*/)service ]]; then
if [[ "$cur" == --?*=* ]]; then
if [[ $ == \~* && $ != */* ]]; then
if type getent &>/dev/null; then
if type perl &>/dev/null; then
if unset -v "$1"; then
if (( $# == 2 )); then
if ! (( $# )); then
echo "bash: ${FUNCNAME[0]}: \`$1': missing" "number specifier" 1>&2;
echo "bash:" "${FUNCNAME[0]}: \`$1': invalid number specifier" 1>&2;
[[ -n "$2" ]] && unset -v "$2" && eval $2=\(\"\${@:3:${1#-a}}\"\) && shift $((${1#-a} + 2)) || {
[[ -n "$2" ]] && unset -v "$2" && eval $2=\"\$3\" && shift 3 || {
if [[ $cur == *@* ]]; then
if [[ $cur = *\\\\* || $cur = *:*:* ]]; then
if [[ $cur = *\\:* ]]; then
if [[ $1 == -u ]]; then
if [[ $cur = *:* ]]; then
if [[ $1 == -u ]]; then
if [[ $1 == -u ]]; then
if [[ $cur =~ ^(\$\{?)([A-Za-z0-9_]*)$ ]]; then
shift;
if [[ -d $xinetddir ]]; then
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# declare -f | grep if #不难发现系统中定义的脚本也有很多if嵌套使用案例
if [ 条件测试表达式 ]
then
条件成立时,执行的源代码。
else
条件不成立时,执行的另一个程序。
fi
[root@node101.yinzhengjie.org.cn ~]# vim shell/file_backup.sh #备份服务器的某个目录
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ll
total
drwxr-xr-x root root Nov : shell
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/file_backup.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/file_backup.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** #同步系统时间,可以先ping通再选择服务器,.cn.pool.ntp.org;.asia.pool.ntp.org;.asia.pool.ntp.org
ntpdate .asia.pool.ntp.org &> /dev/null FilePath="/boot"
BackSave="/root/backup"
date=`date +%F`
size=$(du -sh $FilePath) filename=boot_${date}.tar.gz if [ -d $BackSave ]
then
usleep
else
mkdir $BackSave
fi echo "Date is:$date" > ${BackSave}/backup.log
echo "Size is:$size" >> ${BackSave}/backup.log
tar -zcf ${BackSave}/${filename} ${FilePath} ${BackSave}/backup.log &> /dev/null
rm -f ${BackSave}/backup.log
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/file_backup.sh
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ll
total
drwxr-xr-x root root Nov : backup
drwxr-xr-x root root Nov : shell
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cd backup/
[root@node101.yinzhengjie.org.cn ~/backup]#
[root@node101.yinzhengjie.org.cn ~/backup]# ll
total
-rw-r--r-- root root Nov : boot_2019--.tar.gz
[root@node101.yinzhengjie.org.cn ~/backup]#
[root@node101.yinzhengjie.org.cn ~/backup]# tar zxf boot_2019--.tar.gz
[root@node101.yinzhengjie.org.cn ~/backup]# ll
total
dr-xr-xr-x root root Nov : boot
-rw-r--r-- root root Nov : boot_2019--.tar.gz
drwxr-xr-x root root Nov : root
[root@node101.yinzhengjie.org.cn ~/backup]#
[root@node101.yinzhengjie.org.cn ~/backup]# cat root/backup/backup.log
Date is:--
Size is:113M /boot
[root@node101.yinzhengjie.org.cn ~/backup]#
[root@node101.yinzhengjie.org.cn ~/backup]# ll boot
total
-rw-r--r-- root root Nov config-3.10.-.el7.x86_64
drwxr-xr-x root root Jul : efi
drwxr-xr-x root root Jul : grub
drwx------ root root Jul : grub2
-rw------- root root Jul : initramfs--rescue-9ccdf621e5984f3b8626614f6fa15a48.img
-rw------- root root Jul : initramfs-3.10.-.el7.x86_64.img
-rw------- root root Jul : initramfs-3.10.-.el7.x86_64kdump.img
-rw-r--r-- root root Nov symvers-3.10.-.el7.x86_64.gz
-rw------- root root Nov System.map-3.10.-.el7.x86_64
-rwxr-xr-x root root Jul : vmlinuz--rescue-9ccdf621e5984f3b8626614f6fa15a48
-rwxr-xr-x root root Nov vmlinuz-3.10.-.el7.x86_64
[root@node101.yinzhengjie.org.cn ~/backup]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/file_backup.sh #备份服务器的某个目录
[root@node101.yinzhengjie.org.cn ~]# vim shell/server_alarm.sh #判断某个服务是否启动
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/server_alarm.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/server_alarm.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** Host=127.0.0.1 res=`rpm -qa | grep nmap | head -` if [ -z $res ]
then
yum -y install nmap &> /dev/null
else
echo “准备开始扫描主机服务!”
fi ServiceStatus=$(nmap -sT $Host |grep tcp | grep http|awk '{print $2}') #使用nmap可以准确的判断一台服务器的服务是否正常。 if [ "$ServiceStatus" == "open" ]
then
echo "$(date) httpd is ok !" >> /tmp/HttpdAlarm-acc.log
else
systemctl restart httpd &>/dev/null #注意,如果不是你本机的话,不能直接这么干哟,需要先远程上去再执行命令!
echo "`date` restart httpd!!" >> /tmp/HttpdAlarm-err.log
fi
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN *: *:*
LISTEN ::: :::*
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/server_alarm.sh
“准备开始扫描主机服务!”
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN *: *:*
LISTEN *: *:*
LISTEN ::: :::*
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat /tmp/HttpdAlarm-err.log
Sat Nov :: CST restart httpd!!
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/server_alarm.sh
“准备开始扫描主机服务!”
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat /tmp/HttpdAlarm-acc.log
Sat Nov :: CST httpd is ok !
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/server_alarm.sh #判断某个服务是否启动
[root@node101.yinzhengjie.org.cn ~]# vim shell/ip_judge.sh #判断IP是否合法
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/ip_judge.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/ip_judge.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** read -p "Please input a ip address >>>: " IP
if [[ "$IP" =~ ^(([-]?[-]|[-]{}|[-][-]|[-])\.){}([-]?[-]|[-]{}|[-][-]|[-])$ ]]
then
echo "$IP is legal"
else
echo "$IP is illegal" [root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh
Please input a ip address >>>: 127.0.0.1
shell/ip_judge.sh: line : syntax error: unexpected end of file
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/ip_judge.sh
[root@node101.yinzhengjie.org.cn ~]# cat shell/ip_judge.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/ip_judge.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** read -p "Please input a ip address >>>: " IP
if [[ "$IP" =~ ^(([-]?[-]|[-]{}|[-][-]|[-])\.){}([-]?[-]|[-]{}|[-][-]|[-])$ ]]
then
echo "$IP is legal"
else
echo "$IP is illegal"
fi [root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh
Please input a ip address >>>: 127.0.0.1
127.0.0.1 is legal
[root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh
Please input a ip address >>>: 172.30.1.101
172.30.1.101 is legal
[root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh
Please input a ip address >>>: 192.168.100.1
192.168.100.1 is legal
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh
Please input a ip address >>>: 256.256.256.256
256.256.256.256 is illegal
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh
Please input a ip address >>>: 255.255.255.255
255.255.255.255 is legal
[root@node101.yinzhengjie.org.cn ~]# bash shell/ip_judge.sh
Please input a ip address >>>:
is illegal
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/ip_judge.sh #判断IP是否合法
[root@node101.yinzhengjie.org.cn ~]# vim shell/createuser.sh #编写创建脚本的案例
[root@node101.yinzhengjie.org.cn ~]# cat shell/createuser.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/createuser.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** if [ -z "$1" ];then
read -p "Please input a username >>>: " USER
if [ -z "$USER" ];then
echo "INPUT FLASE"
exit
else
USERNAME=$USER
fi
else
USERNAME=$
fi if id $USERNAME &> /dev/null;then
echo "$USERNAME is exist"
exit
else
useradd $USERNAME && echo "$USERNAME is created"
echo "yinzhengjie" | passwd --stdin $USERNAME &> /dev/null && echo "$USERNAME defalut password: yinzhengjie"
passwd -e $USERNAME
echo userinfo: `id $USERNAME`
fi
[root@node101.yinzhengjie.org.cn ~]# bash -n shell/createuser.sh
[root@node101.yinzhengjie.org.cn ~]# bash shell/createuser.sh
Please input a username >>>: root
root is exist
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/createuser.sh
Please input a username >>>: yinzhengjie
yinzhengjie is exist
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/createuser.sh
Please input a username >>>: jason
jason is created
jason defalut password: yinzhengjie
Expiring password for user jason.
passwd: Success
userinfo: uid=(jason) gid=(jason) groups=(jason)
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# id jason
uid=(jason) gid=(jason) groups=(jason)
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/createuser.sh #编写创建脚本的案例
if [ 条件判断式1 ]
then
当条件判断式1成立时,执行的程序1
elif [ 条件判断式2 ]
then
当条件判断式2成立时,执行程序2
else
当所有条件都不成立时,最后执行此程序
fi 温馨提示:
逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句
[root@node101.yinzhengjie.org.cn ~]# cat shell/judge_filetype.sh #判断用户输入的文件类型
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/judge_filetype.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** read -p "Please input a filename:" file if [ -z "$file" ]
then
echo "Eorr,please input a filename!"
exit
elif [ ! -e "$file" ]
then
echo "Your input is not a file!"
elif [ -f "$file" ]
then
echo "$file is a regulare file!"
elif [ -d "$file" ]
then
echo "$file is direcory!"
else
echo "$file is an other file!"
fi
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/judge_filetype.sh
Please input a filename:/etc/passwd
/etc/passwd is a regulare file!
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/judge_filetype.sh
Please input a filename:/root
/root is direcory!
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/judge_filetype.sh
Please input a filename:/root2
Your input is not a file!
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/judge_filetype.sh #判断用户输入的文件类型
[root@node101.yinzhengjie.org.cn ~]# vim shell/song_of_five_rings.sh #五环之歌小脚本
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/song_of_five_rings.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/song_of_five_rings.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** read -p "Please input your site >>>: " NUM
[[ ! "$NUM" =~ ^[-]+$ ]] && { echo "Please input a digit";exit ;}
if [ "$NUM" -gt ];then
echo "Input false,please a [1-6] interger"
exit
elif [ "$NUM" -eq ];then
echo "more 1 circle than 5"
elif [ "$NUM" -eq ];then
echo "song of five rings"
elif [ "$NUM" -eq ];then
echo "less 1 circle than 5"
elif [ "$NUM" -eq ];then
echo "less 2 circle than 5"
elif [ "$NUM" -eq ];then
echo "less 3 circle than 5"
else
echo "二环是马路,一环是紫禁城!"
fi
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh
Please input your site >>>:
Input false,please a [-] interger
[root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh
Please input your site >>>:
Input false,please a [-] interger
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh
Please input your site >>>:
二环是马路,一环是紫禁城!
[root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh
Please input your site >>>:
less circle than
[root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh
Please input your site >>>:
less circle than
[root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh
Please input your site >>>:
less circle than
[root@node101.yinzhengjie.org.cn ~]# bash shell/song_of_five_rings.sh
Please input your site >>>:
song of five rings
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/song_of_five_rings.sh #五环之歌小脚本
[root@node101.yinzhengjie.org.cn ~]# vim shell/yes_or_no.sh #判断用户输入yes或no
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/yes_or_no.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/yes_or_no.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** read -p "Do you agree?(yes or no)" ANSWER #将用户输入的字母统一转换成小写
lower_answer=`echo $ANSWER | tr 'A-Z' 'a-z'` if [ $lower_answer = "yes" -o $lower_answer = "y" ];then
echo YES
elif [ $lower_answer = "no" -o $lower_answer = "n" ];then
echo NO
else
echo "INPUT FALSE!"
fi
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)y
YES
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)yes
YES
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)no
NO
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)n
NO
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)yesno
INPUT FALSE!
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/yes_or_no.sh #判断用户输入yes或no
[root@node101.yinzhengjie.org.cn ~]# vim shell/score.sh #根据分数来判断绩效
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/score.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/score.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** read -p "Please input your score: " score if [[ ! "$score" =~ ^[-]+$ ]];then
echo "Please input digit"
exit
elif [ "$score" -gt ];then
echo "Your score is invalid!"
exit
elif [ "$score" -lt ];then
echo "绩效为D,不及格"
elif [ "$score" -lt ];then
echo "绩效为C,继续努力"
elif [ "$score" -lt ];then
echo "绩效为B,超出任务预期"
elif [ "$score" -lt ];then
echo "绩效为A,优秀员工"
else
echo "绩效为S,公司骨干人员"
fi
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh
Please input your score: abc
Please input digit
[root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh
Please input your score:
Your score is invalid!
[root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh
Please input your score:
绩效为D,不及格
[root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh
Please input your score:
绩效为C,继续努力
[root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh
Please input your score:
绩效为B,超出任务预期
[root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh
Please input your score:
绩效为A,优秀员工
[root@node101.yinzhengjie.org.cn ~]# bash shell/score.sh
Please input your score:
绩效为S,公司骨干人员
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/score.sh #根据分数来判断绩效
[root@node101.yinzhengjie.org.cn ~]# help case
case: case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac
Execute commands based on pattern matching. Selectively execute COMMANDS based upon WORD matching PATTERN. The
`|' is used to separate multiple patterns. Exit Status:
Returns the status of the last command executed.
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# help case #查看case语句的帮助信息
case $变量名 in
"值1")
如果变量的值等于1,则执行程序1
;;
"值2")
如果变量的值等于2,则执行程序2
;;
"值3")
如果变量的值等于3,则执行程序3
;;
*)
如果变量的值都不是以上的值,则执行此程序
;;
esac 温馨提示:
case语句和if...elif...else语句一样都是多分支条件语句,不过if多分支语句不同的是,case语句只能判断一种条件关系,而if语句可以判断多种条件关系。
case支持glob风格的通配符:
*: 任意长度任意字符
?: 任意单个字符
[]:指定范围内的任意单个字符
a|b: a或b
[root@node101.yinzhengjie.org.cn ~]# vim shell/choose.sh #编写选择的地方并打印
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/choose.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/choose.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** echo "If you want to beijing,please input [1]"
echo "If you want to shanghai,please input [2]"
echo "If you want to shijiazhuang,please input [3]"
echo "If you want to wenzhou,please input [4]" read -t -p "Where do you want to go ? >>> " choose case "$choose" in
"")
echo "Go to beijing!"
;;
"")
echo "Go to shanghai!"
;;
"")
echo "Go to shijiazhuang!"
;;
"")
echo "Go to wenzhou!"
;;
*)
echo "Please enter 1/2/3/4,Thanks!"
;;
esac
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh
If you want to beijing,please input []
If you want to shanghai,please input []
If you want to shijiazhuang,please input []
If you want to wenzhou,please input []
Where do you want to go ? >>>
Go to beijing!
[root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh
If you want to beijing,please input []
If you want to shanghai,please input []
If you want to shijiazhuang,please input []
If you want to wenzhou,please input []
Where do you want to go ? >>>
Go to shanghai!
[root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh
If you want to beijing,please input []
If you want to shanghai,please input []
If you want to shijiazhuang,please input []
If you want to wenzhou,please input []
Where do you want to go ? >>>
Go to shijiazhuang!
[root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh
If you want to beijing,please input []
If you want to shanghai,please input []
If you want to shijiazhuang,please input []
If you want to wenzhou,please input []
Where do you want to go ? >>>
Go to wenzhou!
[root@node101.yinzhengjie.org.cn ~]# bash shell/choose.sh
If you want to beijing,please input []
If you want to shanghai,please input []
If you want to shijiazhuang,please input []
If you want to wenzhou,please input []
Where do you want to go ? >>>
Please enter ///,Thanks!
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/choose.sh #编写选择的地方并打印
[root@node101.yinzhengjie.org.cn ~]# vim shell/yes_or_no.sh #case版本判断用户输入的是yes还是no
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/yes_or_no.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/yes_or_no.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** read -p "Do you agree?(yes or no)" ANSWER case $ANSWER in
[Yy][Ee][Ss]|[Yy])
echo "YES"
;;
[Nn][Oo]|[Nn])
echo "NO"
;;
*)
echo "NOT YES OR NO"
esac
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)y
YES
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)yess
NOT YES OR NO
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)yes
YES
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)no
NO
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)Y
YES
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)Yes
YES
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)No
NO
[root@node101.yinzhengjie.org.cn ~]# bash shell/yes_or_no.sh
Do you agree?(yes or no)ye
NOT YES OR NO
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/yes_or_no.sh #case版本判断用户输入的是yes还是no
[root@node101.yinzhengjie.org.cn ~]# vim shell/menu.sh #编写菜单选择案例
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/menu.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/menu.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** cat <<EOF
鲍鱼
海参
佛跳墙
龙虾
帝王蟹
燕窝
EOF read -p "Choose the menu(1-6): " MENU case $MENU in
|)
echo "The price 100"
;;
|)
echo "The price 150"
;;
|)
echo "The price 80"
;;
*)
echo "Choose false"
;;
esac
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash -n shell/menu.sh #对脚本进行语法检查
[root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh #执行脚本
鲍鱼
海参
佛跳墙
龙虾
帝王蟹
燕窝
Choose the menu(-):
The price
[root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh
鲍鱼
海参
佛跳墙
龙虾
帝王蟹
燕窝
Choose the menu(-):
The price
[root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh
鲍鱼
海参
佛跳墙
龙虾
帝王蟹
燕窝
Choose the menu(-):
The price
[root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh
鲍鱼
海参
佛跳墙
龙虾
帝王蟹
燕窝
Choose the menu(-):
The price
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/menu.sh
鲍鱼
海参
佛跳墙
龙虾
帝王蟹
燕窝
Choose the menu(-):
Choose false
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/menu.sh #编写菜单选择案例
[root@node101.yinzhengjie.org.cn ~]# vim shell/ops_menu.sh #模拟将工作中的任务半自动化,从而提升工作效率。
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# cat shell/ops_menu.sh
#!/bin/bash
#
#********************************************************************
#Author: yinzhengjie
#QQ:
#Date: --
#FileName: shell/ops_menu.sh
#URL: http://www.cnblogs.com/yinzhengjie
#Description: The test script
#Copyright notice: original works, no reprint! Otherwise, legal liability will be investigated.
#******************************************************************** cat <<EOF
ipaddr
yes_or_no
backup
EOF read -p "Please choose the menu[1-3]: " MENU case $MENU in
)
/root/shell/ip_judge.sh
;;
)
/root/shell/yes_or_no.sh
;;
)
/root/shell/file_backup.sh
;;
*)
echo "你的输入不合法!"
exit
;;
esac
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# bash shell/ops_menu.sh
ipaddr
yes_or_no
backup
Please choose the menu[-]:
Please input a ip address >>>: 127.0.0.1
127.0.0.1 is legal
[root@node101.yinzhengjie.org.cn ~]# bash shell/ops_menu.sh
ipaddr
yes_or_no
backup
Please choose the menu[-]:
Do you agree?(yes or no)Y
YES
[root@node101.yinzhengjie.org.cn ~]# bash shell/ops_menu.sh
ipaddr
yes_or_no
backup
Please choose the menu[-]:
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ll
total
drwxr-xr-x root root Nov : backup
drwxr-xr-x root root Nov : shell
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# ll backup/
total
-rw-r--r-- root root Nov : boot_2019--.tar.gz
[root@node101.yinzhengjie.org.cn ~]#
[root@node101.yinzhengjie.org.cn ~]# vim shell/ops_menu.sh #模拟将工作中的任务半自动化,从而提升工作效率。
if语句和case语句用法展示的更多相关文章
- Shell脚本之for循环、while循环,if语句、case语句
1. for循环一般格式: 格式1: for((条件)) do 动作 done 格式2: for 变量名 in 范围 do 动作 done1234567891011121314实验:##1. 输出数字 ...
- 关于shell脚本——条件测试、if语句、case语句
目录 一.条件测试 1.1.表达说明 1.2.test命令 文件测试 1.3.整数值比较 1.4.字符串比较 1.5.逻辑测试 二.if语句 2.1.单分支结构 2.2.双分支结构 2.3.多分支结构 ...
- sql语句判断 case when用法
sql语句判断方法之一 selectcase when t.bk1='on' then 1else 0 end as 基础 ,case when t.bk2='on' then 1else 0 en ...
- Oracle:控制语句 IF..ELSIF语句、CASE语句、FOR循环语句
--多重if语句(注意点:BEGIN END ,IF 条件 THEN,ELSIF 条件 THEN,ELSE... END IF)BEGIN IF FALSE THEN DBMS_OUTPUT.put_ ...
- if语句,case语句
1.句式:if...then.判断赋值 例: if RadioButton1.Checked then sex:='男' else if RadioButton2.Checked then sex:= ...
- Shell Scripts - 条件语句,case语句,function功能
修改之前的代码 1.判断 $1 是否为 hello,如果是的话,就显示 "Hello, how are you ?": 2.如果没有加任何参数,就提示使用者必须要使用的参数 ...
- Java基础之循环语句、条件语句、switch case 语句
Java 循环结构 - for, while 及 do...while 顺序结构的程序语句只能被执行一次.如果您想要同样的操作执行多次,,就需要使用循环结构. Java中有三种主要的循环结构: whi ...
- JavaScript基础知识(if、if else、else if、while、switch...case语句)
13.语句 概念:就是分号(:) 代表一条语句的结束 习惯:一行只编写一条语句:一行编写多条语句(代码可读性较差) 语句块:可以包含多条语句 "{ }"将多条语句包裹 u ...
- MySQL存储过程 CASE语句
MySQL存储过程 CASE语句 除了IF语句,MySQL提供了一个替代的条件语句CASE. MySQL CASE语句使代码更加可读和高效. CASE语句有两种形式:简单的搜索CASE语句. 简单C ...
随机推荐
- 读书笔记(chapter17)
设备类型:在所有Unix系统中为了统一普通设备的操作所采用的分类 模块:Linux内核中用于按需加载和卸载目标码的机制 内核对象:内核数据结构中支持面对对象的简单操作,还支持维护对象之间的父子关系 1 ...
- personal project
words count program 统计文本文件的字符数,单词数和行数. 实现一个统计程序,他能正确的统计程序文件中的字符数,单词数和行数. 源码链接 https://github.com/sup ...
- multer处理post请求的代码演示
let express = require('express'); let multer = require('multer'); let mObj = multer({dest:__dirname+ ...
- python matplotlib绘图
import numpy as np import matplotlib.pyplot as plt from scipy.constants.constants import alpha from ...
- python自动化运维笔记1 —— 系统性能信息模块psutil
一.系统基础信息模块 1.1 系统性能信息模块psutil psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率( ...
- 一对一 只需将另一个表的id设置为主键和外键即可
一对一 只需将另一个表的id设置为主键和外键即可
- BZOJ3207花神的嘲讽计划Ⅰ——主席树+hash
题目描述 背景 花神是神,一大癖好就是嘲讽大J,举例如下: “哎你傻不傻的![hqz:大笨J]” “这道题又被J屎过了!!” “J这程序怎么跑这么快!J要逆袭了!” …… 描述 这一天DJ在给吾等众蒟 ...
- UUID类型如何比较是否相等
直接使用equals方法 UUID x = UUID.fromString("062db347-6a72-69a1-40c0-7516e0a26459"); UUID y = UU ...
- MT【234】正方形染色(二)
有$n$个正方形排成一行,今用红,白,黑三种颜色给这$n$个正方形染色,每个正方形只能染一种颜色.如果要求染这三种颜色的正方形都是偶数个,问有多少种不同的染色方法. 解答: 设有$a_n$种不同的染法 ...
- 学习Spring Boot:(二十八)Spring Security 权限认证
前言 主要实现 Spring Security 的安全认证,结合 RESTful API 的风格,使用无状态的环境. 主要实现是通过请求的 URL ,通过过滤器来做不同的授权策略操作,为该请求提供某个 ...