温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Unix脚本编程,入门指南在这里!

发布时间:2025-11-20 11:08:35 来源:亿速云 阅读:128 作者:小樊 栏目:系统运维

Unix Shell 脚本入门指南

一 环境准备与第一个脚本

  • 确认环境:在终端执行 echo $SHELL 查看当前 Shell;大多数 Linux 默认是 Bash。Windows 可使用 CygwinWSL 搭建类 Unix 环境。
  • 创建脚本:新建文件 hello.sh,写入以下内容:
    #!/bin/bash
    # 第一个 Shell 脚本
    echo "Hello, $USER!"
    
  • 赋予权限并执行:
    chmod +x hello.sh    # 添加可执行权限
    ./hello.sh           # 执行脚本
    bash hello.sh        # 直接用 bash 解释器运行(无需 +x)
    source hello.sh      # 或 . hello.sh,在当前 Shell 中执行
    
  • 要点:第一行 #!/bin/bashShebang,用于指定解释器;脚本通常以 .sh 结尾(非强制)。

二 核心语法速览

  • 变量与引用:
    name="Alice"
    echo "Hello, $name"    # 变量引用
    readonly PI=3.14       # 只读变量
    arr=(a b c)           # 数组
    echo "${arr[1]}"      # 数组下标从 0 开始
    
  • 用户输入:
    read -p "Name: " name
    echo "Hi, $name"
    
  • 条件判断:
    if [ -f "$file" ]; then
      echo "$file exists."
    elif [ -d "$file" ]; then
      echo "$file is a directory."
    else
      echo "$file not found."
    fi
    
  • 循环:
    # for 遍历通配符更安全(避免 for f in $(ls *.txt) 的陷阱)
    for f in *.txt; do
      [ -e "$f" ] || continue   # 若无匹配文件,防止字面量 *.txt 被处理
      echo "Processing $f"
    done
    
    # while 计数
    i=1
    while [ $i -le 5 ]; do
      echo "$i"
      ((i++))
    done
    
  • 函数:
    greet() {
      local name="$1"   # 局部变量
      echo "Hello, $name"
    }
    greet "Bob"
    
  • 管道与重定向:
    # 统计 .sh 文件行数
    find . -name "*.sh" -type f | xargs wc -l
    
    # 日志追加
    echo "[$(date)] Start" >> app.log 2>&1
    
  • 要点:条件测试常用 [ ]-f/-d/-z 等;循环遍历文件建议用通配符而非解析 ls;重定向 2>&1 将标准错误合并到标准输出。

三 实战示例 日志分析小工具

  • 需求:统计指定日志中 ERROR 出现次数,并列出前 5 条匹配行的时间与内容。
  • 脚本 logerr.sh
    #!/usr/bin/env bash
    # 用法:./logerr.sh <日志文件> [关键字=ERROR] [top=N]
    
    set -euo pipefail   # 严格模式:遇错退出、未定义变量报错、管道错误传播
    
    file="${1:-}"
    keyword="${2:-ERROR}"
    top="${3:-5}"
    
    if [ ! -f "$file" ]; then
      echo "Usage: $0 <log-file> [keyword=ERROR] [top=N]" >&2
      exit 1
    fi
    
    echo "=== $keyword count ==="
    grep -i "$keyword" "$file" | wc -l
    
    echo -e "\n=== Top $top $keyword lines ==="
    grep -i "$keyword" "$file" \
      | sed 's/^\([^ ]\{1,\} [^ ]\{1,\} [^ ]\{1,\}\) .*/\1/' \
      | sort \
      | uniq -c \
      | sort -nr \
      | head -n "$top" \
      | sed 's/^ *\([0-9]\+\) /\1: /'
    
  • 运行示例:
    chmod +x logerr.sh
    ./logerr.sh app.log ERROR 10
    
  • 要点:使用 set -euo pipefail 提高健壮性;通过 grep | sed | sort | uniq -c | sort -nr | head 组合常见文本处理命令完成统计与筛选。

四 调试与最佳实践

  • 调试技巧:
    • 开启调试:在脚本顶部加入 set -x,或在执行时 bash -x script.sh
    • 严格模式:使用 set -euo pipefail 捕获未定义变量与管道错误。
    • 观察退出码:命令后 || { echo “Failed: $?”; exit 1; }
  • 代码规范:
    • 命名:变量/函数使用小写与下划线,如 cpu_threshold=80
    • 引用:变量与路径一律加引号,如 “$file”
    • 注释:关键逻辑与复杂代码块前添加注释。
    • 避免“魔法数字”,抽取为具名常量。
  • 性能与可移植性:
    • 遍历文件用通配符 *for f in .txt,避免解析 ls
    • 将循环内不变计算移到外面,减少重复运算。
    • 尽量使用 /usr/bin/env bash 提升可移植性;注意 bashsh 语法差异。
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI