首页 > 系统相关 >Shell 脚本(Bash 版)

Shell 脚本(Bash 版)

时间:2024-04-30 13:22:06浏览次数:22  
标签:脚本 Shell name number echo Bash bash

0x01 概述

(1)Shell 简介

  • Shell 是一个命令行解释器

    flowchart LR 用户输入命令-->接收并将命令传递给内核执行-->将命令执行的结果返回给用户
  • Shell 种类丰富,包括 sh、csh、ksh、bash、zsh、fish 等

    • 以下内容使用的是 bash(Bourne Again Shell)
    • Linux 系统中默认安装的是 bash
    • Windows 中使用的是 PowerShell,可以通过 WSL 或 Git Bash 在 Windows 系统中使用 bash

(2)查看 Shell 相关信息

  • cat /etc/shells:查看系统中所有的 Shell 版本
  • echo $SHELL:当前系统默认使用的 Shell,类似形式的命令有:
    • echo $0:查看当前正在执行的脚本名称
    • echo $HOME:查看当前用户的家目录
    • echo $PATH:查看系统的查找路径

(3)编写 Shell 脚本

  • 对于需要批量执行的命令,可以保存在 Shell 脚本中,从而实现自动化

  • Shell 脚本文件的扩展名一般为 .sh,也可以是其它扩展名

  • 编写脚本:

    1. 新建脚本文件

      touch hello.sh
      
    2. 使用 Vi 编辑脚本

      vi hello.sh
      
    3. i 键进入编辑模式(Vi 编辑器使用方法见Vim 安装与基础操作指南 | 博客园-SRIGT

    4. 第一行一般是用于指定使用的 Shell 种类

      #!/bin/bash
      
    5. 之后写入需要执行的命令,默认自上向下依次执行

      echo "Hello, shell script"	# 文本输出
      date	# 日期与时间
      whoami	# 当前用户名
      
    6. 依次按 [ESC]:wq 保存脚本并退出 Vi 编辑器

    7. 使用命令 chmod a+x hello.sh 修改脚本文件执行权限

    8. 使用命令 ./hello.sh 执行该脚本

  • Shell 脚本中,支持使用条件语句、循环语句、函数、局部变量等

    • 举例:素数判断脚本

      #!/bin/bash
      is_prime() {
          local num=$1
          if [ $num -lt 2 ]; then
              return 1
          fi
      
          for ((i=2; i*i<=num; i++)); do
              if [ $((num % i)) -eq 0 ]; then
                  return 1
              fi
          done
          return 0
      }
      
      read -p "输入一个正整数: " number
      if is_prime $number; then
          echo "$number 是素数"
      else
          echo "$number 不是素数"
      fi
      

0x02 脚本基础

案例:使用 bash 编写 Shell 脚本实现“猜数游戏”

(1)输入与输出

#!/bin/bash

read -p "输入用户名: " name
echo "欢迎,$name"
  • read -p "提示内容" 变量名
  • echo "输出内容 $变量名"
#!/bin/bash

name=$1
echo "欢迎,$name"
  • 使用命令 ./game.sh SRIGT 执行脚本并设置第一个参数为 SRIGT
  • name=$1:将第一个参数赋值给变量 name
    • $1~$n 分别表示第 \(n\) 个参数
    • $#:传递给脚本或函数位置参数的个数
    • $*:传递给脚本或函数的位置参数,双引号包围时作为一个整体
    • $@:传递给脚本或函数的位置参数
    • $$:当前 Shell 进程的 PID
    • $!:最后一个后台命令的 PID
    • $?:上一命令的退出状态码

(2)变量

  • 定义环境变量

    name=SRIGT
    echo $name
    
  • 在 Shell 脚本中使用环境变量的值

    export name=SRIGT
    
    # game.sh
    #!/bin/bash
    
    echo "欢迎,$name"
    
  • 将自定义的环境变量永久保存

    cd /etc/bash
    vi bash.bashrc
    
    # bash.bashrc
    # 在文件的最后写入以下内容
    export name=SRIGT
    
    source bash.bashrc
    . bash.bashrc
    

(3)随机数

number=$(shuf -i 1-10 -n 1)
  • shuf -i 生成范围 -n 生成个数

  • 在 Shell 脚本中,须要使用 $(命令) 或反引号将命令作为一个整体来处理

number=$((RANDOM % 10 + 1))
  • $RANDOM:会随机生成 \(0-32767\) 之间的随机数

(4)条件判断

if [[ $guess -eq $number ]]; then
        echo "猜中了"
elif [[ $guess -lt $number ]]; then
        echo "猜小了"
elif [[ $guess -gt $number ]]; then
        echo "猜大了"
else
        echo "猜错了"
fi
  • 条件判断语法

    if condition; then
    	# 语句
    elif condition; then
    	# 语句
    else
    	# 语句
    if
    
  • 条件测试表达式 condition 可以是:

    • []:最基本的条件测试表达式
    • [[]]:扩展测试命令
    • (()):数学表达式,支持加减乘除等常见的数学运算

(5)循环

while true
    do
    read -p "输入1-10之间的数字作为猜数: " guess
    if [[ $guess -eq $number ]]; then
        read -p "猜中了, 是否继续(y/n)" choice
        if [[ $choice = "y" ]] || [[ $choice = "Y" ]]; then
            number=$(shuf -i 1-10 -n 1)
            continue
        else
            break
        fi
    fi
    done
  • for 循环语法:

    for ((condition 1; condition 2; condition 3)); do
    	# 语句
    done
    
  • while 循环语法:

    while condition
    do
    	# 语句
    done
    
  • continue:继续循环

  • break:跳出循环

完整代码

#!/bin/bash

echo "欢迎,$name"
number=$(shuf -i 1-10 -n 1)
while true
    do
    read -p "输入1-10之间的数字作为猜数: " guess
    if [[ $guess -eq $number ]]; then
        read -p "猜中了, 是否继续(y/n)" choice
        if [[ $choice = "y" ]] || [[ $choice = "Y" ]]; then
            number=$(shuf -i 1-10 -n 1)
            continue
        else
            break
        fi
    elif [[ $guess -lt $number ]]; then
        echo "猜小了"
    elif [[ $guess -gt $number ]]; then
        echo "猜大了"
    else
        echo "猜错了"
    fi
    done

-End-

标签:脚本,Shell,name,number,echo,Bash,bash
From: https://www.cnblogs.com/SRIGT/p/18167861

相关文章

  • python脚本获取当前浏览器客户端的公共ip以及其详细信息
    python脚本获取当前客户端的公共ip以及其详细信息importrequestsfromflaskimportFlask,request,make_response,send_from_directoryfromdatetimeimportdatetimeimportasynciofromhypercorn.asyncioimportservefromhypercorn.configimportConfigimportos......
  • ansible 常用模块 shell
    shell模块说明shell模块用于在目标主机上执行命令,类似于在命令行中直接输入命令。这个模块允许你执行任何命令,但是要注意命令的安全性和可重复性。shell模块语法-name:Executeshellcommandansible.builtin.shell:cmd:<command>chdir:<directory>#......
  • LD链接脚本
    LinkerScripts语法解析本文主要翻译自Top(LD)(sourceware.org)第三章,链接脚本。因此下面目录均以3开头目录LinkerScripts语法解析3前言3.1BasicLinkerScriptConcepts3.2LinkerScriptFormat3.3SimpleLinkerScriptExample3.4SimpleLinkerScriptCommands3.4.1......
  • shell 命令专栏总结
    一、菜鸟教程1、只读变量readonly使用readonly命令可以将变量定义为只读变量,只读变量的值不能被改变。#!/bin/bashmyUrl="https://www.google.com"readonlymyUrlmyUrl="https://www.runoob.com"/bin/sh:NAME:Thisvariableisreadonly.2、单引号与双引号的区别......
  • curl多请求脚本
    #!/bin/bash#定义请求URL和数据url="https://api-adservices.apple.com/api/v1"data=""output_file="requests_log.txt"#清空或创建输出文件>"$output_file"#函数用于发送POST请求并记录日志send_post_request(){localrequest_number=$1local......
  • 21-Shell编程
    21.1正则表达式21.1.4字符集和单词“单词”指的是两侧由非单词字符分隔的字符串。非单词字符指的是字母、数字、下划线以外的任何字符。21.1.5字符类POSIX正则表达式中的字符类类匹配字符[[:alnum:]]文字、数字字符[[:alpha:]]字母字符[[:lower:]]小写......
  • linux修改shell,以及安装zsh配置oh-my-zsh.md
    查看当前shellecho$SHELL查看系统中有哪些shellcat/etc/shells修改shell,输入要切换的shell,例/bin/zshchsh-s/bin/zsh安装zshyuminstall-yzshoh-my-zsh克隆zshgitclonehttps://github.com/robbyrussell/oh-my-zsh.git~/.oh-my-zshgithub拉不下来的话去gitee......
  • 1-Linux集群搭建,分发脚本,ssh免密登录
    Linux集群部署集群规划模板机安装创建完成后全部打开并登录root账户修改克隆主机名vim/etc/sysconfig/network-scripts/ifcfg-ens33esc退出并输入:wq保存按i修改IPADDR为192.168.10.101/192.168.10.102/192.168.10.103vim/etc/hostname按i修改名字......
  • 《最新出炉》系列入门篇-Python+Playwright自动化测试-40-录制生成脚本
    https://www.cnblogs.com/du-hong/p/17835463.html 1.简介各种自动化框架都会有脚本录制功能,playwright这么牛叉当然也不例外。很早之前的selenium、Jmeter工具,发展到每种浏览器都有对应的录制插件。今天我们就来看下微软自动化框架playwright是如何录制脚本的。很多小伙伴或......
  • 应急响应-webshell查杀
    简介靶机账号密码rootxjwebshell1.黑客webshell里面的flagflag{xxxxx-xxxx-xxxx-xxxx-xxxx}2.黑客使用的什么工具的shellgithub地址的md5flag{md5}3.黑客隐藏shell的完整路径的md5flag{md5}注:/xxx/xxx/xxx/xxx/xxx.xxx4.黑客免杀马完整路径md5flag步骤#1.1......