草庐IT

Shell---控制流程

sre-chan 2023-03-28 原文

操作系统:

RHEL7.x 或CentOS 7.x

  • 最小化安装
  • 配置好固定的IP,能访问互联网
  • 配置好yum源(yum repolist 可以查看yum源)
    • 本地光盘
      • 挂载光盘,开机自动挂载
        • vim + /etc/fstable
        • /dev/sr0 /mnt iso9660 defaults 0 0
      • 创建挂载点目录:
        • mkdir /media/cdrom
      • 挂载:mount -a
      • 配置yum源:
        • yum-config-manger --add-repo=file:/// media/cdrom
        • echo "gpgcheck = 0" >> /etc/yum.repos.d/media_cdrom.repo
    • EPEL
      • aliyun sohu 中科大 清华 网易

开发环境:vim

查看系统shell类型:

[root@template ~]# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash

查看当前默认shell:

[root@template ~]# echo $SHELL
/bin/bash

快速如何快速生成脚本开头的版本版权注释信息

[root@template ~]# cat ~/.vimrc
autocmd BufNewFile *.go,*.py,*.cc,*.sh,*.java exec ":call SetTitle()"
func SetTitle()
if expand("%:e") == 'sh'
call setline(1,"#!/bin/bash")
call setline(2,"#########################")
call setline(3,"#File name:".expand("%"))
call setline(4,"#Version:v1.0")
call setline(5,"#Email:admin@test.com")
call setline(6,"#Created time:".strftime("%F %T"))
call setline(7,"#Description:")
call setline(8,"#########################")
call setline(9,"")
endif
endfunc

修改Tab缩进

在/etc/vim/下有两个文件,分别为vimrc 和vimrc.tiny

在vimrc文件中加入:set tabstop=4

流程控制与判断练习:

1、ping主机测试,查看主机是否存活

[root@template chap04]# cat ping.sh
#!/bin/bash
#########################
#File name:ping.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-03-23 17:32:18
#Description:
#########################
read -p "please enter your host:" host
if ping -c2 $host &> /dev/null
then
        echo "$host is running"
else
        echo "$host is down"
fi

2、判断一个用户是否存在

[root@template chap04]# cat user.sh
#!/bin/bash
#########################
#File name:user.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-03-23 17:45:03
#Description:
#########################
read -p "please enter a username:" username
if id $username &> /dev/null
then
        echo "$username is exist"
else
        echo " $username is not exist "
fi

3、判断当前内核主版本是否为3,且次版本是否大于10

[root@template chap04]# cat sys.sh
#!/bin/bash
#########################
#File name:sys.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-03-23 17:52:56
#Description:
main_version=`uname  -r | awk -F . '{print $1 }'`
minor_version=`uname -r | awk -F . '{print $2}'`
if [ "$main_version"  -eq 3 ] && [ "$minor_version" -ge 10 ]
  then
     echo "主版本是:$main_version 次版本是:$minor_version"
else
       echo "不满足条件,此系统的主版本是:$main_version 次版本是:$minor_version"
fi

4、判断vsftpd软件包是否安装,如果没有则自动安装

#!/bin/bash
#########################
#File name:isvsftp.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-03-23 18:05:56
#Description:
#########################
if rpm -qa | grep vsftpd &> /dev/null
then
        echo "vsftp is exist"
else
        echo "vsftp is not exist"
        read -p "please enter your choice:" choice
        if [ $choice -eq 1 ]
                then
                        yum install vsftpd -y &> /dev/null
        else
                echo " break and uninstall"
        fi
fi

# 测试结果:最初环境没有安装,选择时随机输入,最后选择安装,最后一次测试检查是否安装成
[root@template chap04]# ./isvsftp.sh
vsftp is not exist
please enter your choice:2
 break and uninstall
[root@template chap04]# ./isvsftp.sh
vsftp is not exist
please enter your choice:1
[root@template chap04]# ./isvsftp.sh
vsftp is exist

5、判断httpd是否运行

# 也不算完整:先检测是否安装htppd.service此软件,注意centos7版本中自带一个httpd-xxx的工具,所以在写服务时最好加上httpd.service,程序流程:如果包存在,直接输出active,如果不存在就选择是否安装
[root@template chap04]# cat httpd.sh
#!/bin/bash
#########################
#File name:httpd.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-03-23 18:20:59
#Description:
#########################
if rpm -qa |  grep httpd.service &> /dev/null
then
        echo "system  `systemctl is-active httpd`"
else
        echo "httpd is uninstall"
        read -p " please enter your choice : " choice
        if [ $choice -eq 1 ]
        then
                yum install httpd -y &> /dev/null
                systemctl restart httpd
        else
                echo " break and uninstall"
        fi
fi

6、判断指定的主机是否能ping通,必须使用$1变量

[root@template chap04]# cat ping2.sh
#!/bin/bash
#########################
#File name:ping2.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2023-03-23 18:55:21
#Description:
#########################
if ping -c1 $1 &> /dev/null
then
        echo "$1 is runing"
else
        echo "$1 is dead"
fi

[root@template chap04]# ./ping2.sh  192.168.11.10
192.168.11.10 is runing
[root@template chap04]# ./ping2.sh  baidu.com
baidu.com is runing

7、报警脚本,要求如下

根分区剩余空间小于20%
内存已用空间大于80%
向用户alice发送告警邮件
配合crond每5分钟检查一次

yum install mailx -y &> /dev/null
#!/bin/bash
total_mem=$(free -m | tr -s " " | cut -d " " -f 2 | head -2 | tail -1)
used_mem=$(free -m | tr -s " " | cut -d " " -f 3 | head -2 | tail -1)
used_memper=$(echo "scale=2;$used_mem/$total_mem*100" | bc)
total_root=$(df | grep "/"$ |tr -s " " | cut -d " " -f 2)
used_root=$(df | grep "/"$ |tr -s " " | cut -d " " -f 4)
free_rootper=$(echo "scale=2;$used_root/$total_root*100" | bc)
v1=$(echo "used_memper > 80" | bc)
v2=$(echo "free_rootper < 20" | bc)
if [ $v1 -eq 1 ];then
  echo "内存已用空间大于80%" | mail -s "警告信息" alice
elif [ $v2 -eq 1 ];then
  echo "根分区剩余空间小于20%" | mail -s "警告信息" alice
else
  echo "正常使用"
fi

8、判断用户输入的是否是数字,如果是数字判断该数字是否大于10

[root@template chap04]# cat num.sh
#!/bin/bash
read -p "please input a num:" num
if echo  " $num" | grep " [ 0-9 ]" &> /dev/null
then
        if [ $num -gt 10 ]
        then
                echo "$num is more than 10"
        else
                echo "$num is less than 10"

        fi
else
        echo "input a num!!!"
fi

9、计算用户输入的任意两个整数的和、差、乘积、商、余数

a=$1
b=$2
if [ $# -eq 2 ]
then
  if [[ "$a" =~ ^[0-9]*$ && "$b" =~ ^[0-9]*$ ]]
  then
    echo "a、b Is an integer"
    echo a+b=$((a+b))
    echo a-b=$((a-b))
    echo a*b=$((a*b))
    echo a/b=$((a/b))
    echo a%b=$((a%b))
  else
    echo "a,b Is  not an integer"
    exit 0
  fi
else
  echo "The number of parameters is 2"
  exit 0
fi

有关Shell---控制流程的更多相关文章

  1. Ruby Readline 在向上箭头上使控制台崩溃 - 2

    当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby​​安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少

  2. ruby-on-rails - 带 Spring 锁的 Rails 4 控制台 - 2

    我正在使用Ruby2.1.1和Rails4.1.0.rc1。当执行railsc时,它被锁定了。使用Ctrl-C停止,我得到以下错误日志:~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`gets':Interruptfrom~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`verify_server_version'from~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.

  3. ruby-on-rails - 如何在 ruby​​ 交互式 shell 中有多行? - 2

    这可能是个愚蠢的问题。但是,我是一个新手......你怎么能在交互式ruby​​shell中有多行代码?好像你只能有一条长线。按回车键运行代码。无论如何我可以在不运行代码的情况下跳到下一行吗?再次抱歉,如果这是一个愚蠢的问题。谢谢。 最佳答案 这是一个例子:2.1.2:053>a=1=>12.1.2:054>b=2=>22.1.2:055>a+b=>32.1.2:056>ifa>b#Thecode‘if..."startsthedefinitionoftheconditionalstatement.2.1.2:057?>puts"f

  4. ruby-on-rails - openshift 上的 rails 控制台 - 2

    我将我的Rails应用程序部署到OpenShift,它运行良好,但我无法在生产服务器上运行“Rails控制台”。它给了我这个错误。我该如何解决这个问题?我尝试更新ruby​​gems,但它也给出了权限被拒绝的错误,我也无法做到。railsc错误:Warning:You'reusingRubygems1.8.24withSpring.UpgradetoatleastRubygems2.1.0andrun`gempristine--all`forbetterstartupperformance./opt/rh/ruby193/root/usr/share/rubygems/rubygems

  5. ruby-on-rails - rbenv:从 RVM 移动到 rbenv 后,在 Jenkins 执行 shell 中找不到命令 - 2

    我从Ubuntu服务器上的RVM转移到rbenv。当我使用RVM时,使用bundle没有问题。转移到rbenv后,我在Jenkins的执行shell中收到“找不到命令”错误。我内爆并删除了RVM,并从~/.bashrc'中删除了所有与RVM相关的行。使用后我仍然收到此错误:rvmimploderm~/.rvm-rfrm~/.rvmrcgeminstallbundlerecho'exportPATH="$HOME/.rbenv/bin:$PATH"'>>~/.bashrcecho'eval"$(rbenvinit-)"'>>~/.bashrc.~/.bashrcrbenvversions

  6. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  7. ruby-on-rails - 在 Rails 控制台中使用 asset_path - 2

    在我的Character模型中,我添加了:字符.rbbefore_savedoself.profile_picture_url=asset_path('icon.png')end但是,对于数据库中已存在的所有角色,它们的profile_picture_url为nil。因此,我想进入控制台并遍历所有这些并进行设置。在我试过的控制台中:Character.find_eachdo|c|c.profile_picture_url=asset_path('icon.png')end但这给出了错误:NoMethodError:undefinedmethod`asset_path'formain:O

  8. ruby - 从 Ruby : capturing the output while displaying the output? 运行 shell 命令 - 2

    我有一个问题。我想从另一个ruby​​脚本运行一个ruby​​脚本并捕获它的输出信息,同时让它也输出到屏幕。亚军#!/usr/bin/envrubyprint"Enteryourpassword:"password=gets.chompputs"Hereisyourpassword:#{password}"我运行的脚本文件:开始.rboutput=`runner`putsoutput.match(/Hereisyour(password:.*)/).captures[0].to_s正如您在此处看到的那样,存在问题。在start.rb的第一行,屏幕是空的。我在运行程序中看不到“输入您的密

  9. ruby-on-rails - 带有 Pry 的 Rails 控制台 - 2

    当我进入Rails控制台时,我已将pry设置为加载代替irb。我找不到该页面或不记得如何将其恢复为默认行为,因为它似乎干扰了我的Rubymine调试器。有什么建议吗? 最佳答案 我刚发现问题,pry-railsgem。忘记了它的目的是让“railsconsole”打开pry。 关于ruby-on-rails-带有Pry的Rails控制台,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/question

  10. ruby - 将全局 $stdout 重新分配给控制台 - ruby - 2

    我正在尝试将$stdout设置为临时写入一个文件,然后返回到一个文件。test.rb:old_stdout=$stdout$stdout.reopen("mytestfile.out",'w+')puts"thisgoesinmytestfile"$stdout=old_stdoutputs"thisshouldbeontheconsole"$stdout.reopen("mytestfile1.out",'w+')puts"thisgoesinmytestfile1:"$stdout=old_stdoutputs"thisshouldbebackontheconsole"这是输出。r

随机推荐