1.检查用户家目录中的 test.sh 文件是否存在,并且检查是否有执行权限

<pre class="brush:bash;gutter:true;">#!/bin/bash
if [ -e ~/test.sh ];then
   echo "test.sh文件存在"
   if [ -x ~/test.sh ];then
      echo "test.sh文件有执行权限"
   else
      echo "test.sh文件没有执行权限"
   fi
else
  echo "test.sh文件不存在"
fi

shell脚本练习1——条件语句(if 、case语句的应用)教程

2.提示用户输入100米赛跑的秒数,要求判断秒数大于0且小于等于10秒的进入选拔赛,大于10秒的都淘汰,如果输入其它字符则提示重新输入;进入选拔赛的成员再进一步判断男女性别,男生进男生组,女生进女生组,如果输入错误请提示错误

<pre class="brush:bash;gutter:true;">#!/bin/bash
read -p "请输入你100米赛跑的秒数:" time
if [ $time -gt 0 -a $time -le 10 ];then
   echo "恭喜你进入选拔赛"
read -p "请输入你的性别(女或者男)" sex
   if [ $sex = '女' ];then
      echo "恭喜你进入女生组"
   elif [ $sex = '男' ];then
      echo "恭喜你进入男生组"
   else
      echo "输入有误!"
   fi
elif [ $time -gt 10 ];then
   echo "很遗憾,你已被淘汰"
else
   echo "输入有误,请重新输入"
fi

shell脚本练习1——条件语句(if 、case语句的应用)教程

3.用case语句解压根据输入的后缀名为 .tar.gz 或 .tar.bz2 的压缩包解压到 /opt 目录

3.1 使用位置变量

<pre class="brush:bash;gutter:true;">#!/bin/bash
case $1 in
*.gz)
  tar zxvf $1 -C /opt
;;
*.bz2)
  tar jxvf $1 -C /opt
;;
*)
  echo "格式错误"
;;
esac

shell脚本练习1——条件语句(if 、case语句的应用)教程

3.2 使用read -p 获得用户输入的信息

shell脚本练习1——条件语句(if 、case语句的应用)教程


4、提示用户输入内容,使用if 语句判断输入的内容是否为整数,再判断输入的内容是奇数还是偶数。

<pre class="brush:bash;gutter:true;">#!/bin/bash
# this is determine the odd number of documents

read -p "请输入一个数: " num

expr $num + 0 &> /dev/null

if [ $? -eq 0 ];then
        echo "$num是整数!"
        a=$[ $num % 2 ]
        if [ $a -eq 0 ]
        then
          echo "$num是偶数"
        else
          echo "$num是奇数"
        fi
else
  echo 你输入的不是整数!
fi

shell脚本练习1——条件语句(if 、case语句的应用)教程

5、用if 语句判断主机是否存活

<pre class="brush:bash;gutter:true;">#!/bin/bash
#Determine whether the host is alive

ping -c 3 -i 0.5 -w 2 $1 &> /dev/null

if [ $? -eq 0 ];then
   echo "host is online"
else
   echo "host is offline"
fi

shell脚本练习1——条件语句(if 、case语句的应用)教程

6.用case语句在/etc/init.d/目录中写一个firewalld脚本,并加入到系统服务管理中

使能够使用 service firewalld start|stop|restart|status 来管理firewalld服务,
要求如果命令选项不对,则提示 “用法: $0 {start|stop|status|restart}”。

<pre class="brush:bash;gutter:true;">#!/bin/bash
#Administrative firewalld

read -p "请输入管理防火墙的需求(start|stop|restart|status):" need

case $need in
start)
     systemctl start firewalld
     echo "防火墙已开启"
;;
stop)
    systemctl stop firewalld
    echo "防火墙已关闭"
;;
restart)
    systemctl restart firewalld
    echo "防火墙已重启"
;;
status)
    systemctl status firewalld
    echo "查看防火墙状态"
;;
*)
   echo "用法: $0 {start|stop|status|restart}"
esac

shell脚本练习1——条件语句(if 、case语句的应用)教程

shell脚本练习1——条件语句(if 、case语句的应用)教程

标签: shell, echo, firewalld, 输入, fi, 语句, case, else, test

相关文章推荐

添加新评论,含*的栏目为必填