惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
Google DeepMind News
Google DeepMind News
Hugging Face - Blog
Hugging Face - Blog
D
Docker
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Simon Willison's Weblog
Simon Willison's Weblog
S
Security Affairs
NISL@THU
NISL@THU
T
Tor Project blog
A
About on SuperTechFans
宝玉的分享
宝玉的分享
腾讯CDC
S
Schneier on Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Privacy & Cybersecurity Law Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
P
Privacy International News Feed
雷峰网
雷峰网
C
Cyber Attacks, Cyber Crime and Cyber Security
Vercel News
Vercel News
Cisco Talos Blog
Cisco Talos Blog
D
DataBreaches.Net
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
L
LINUX DO - 热门话题
Microsoft Security Blog
Microsoft Security Blog
Latest news
Latest news
C
Check Point Blog
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
爱范儿
爱范儿
月光博客
月光博客
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
P
Palo Alto Networks Blog
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs

博客园 - 干炸小黄鱼

timex 处理时间戳 gorm-gen go 雪花算法 golang每日一库--协程池库ants golang每日一库--json解析库gjson python高级编程-asyncio python高级编程-condition python高级编程-event python装饰器-自动重试 EAP系统 go实现实现 SECS/GEM 协议 设备通信协议 SECS go项目使用Jenkins进行CICD go操作ES mongo db聚合查询 go如何使用mongodb Apache ShardingSphere paxos and raft (分布式一致性算法) go使用zookeeper分布式锁以及和redis差异 go使用 seata 示例 Alibaba 分布式事务 Seata go中使用saga go中使用TCC示例 分布式事务TCC 熔断器 Hystrix OR Sentinel k8s下部署consul and etcd Consul OR Etcd 【力扣hot100】双指针-盛水最多的容器 【力扣hot100】滑动窗口-最小覆盖子串 分布式id生成器 springboot通用CURD Python PB级检索系统架构设计 rancher 在三台机器搭建k8s集群 python ssh clinet 数据库排序Null值字段靠后/靠前 常规web项目 docker-compose 例子 手搓一个验证码 使用itertools 中的groupby 对字典数组进行分组后排序 使用开源库 geoip2 获取某ip的经纬度地理信息 python中 apscheduler.schedulers.blocking.BlockingScheduler 定时执行任务 简单的python web项目的docker-compose.yml 示例 python和sliver交互 golang sliver二次开发自定义命令(格式乱后面再调) pydantic做参数校验 基于rancher部署k8s 地理位置相关基础数据 flask migrate时报错 Can't locate revision identified by '3d80e4c025df'
shell脚本合集
干炸小黄鱼 · 2026-04-12 · via 博客园 - 干炸小黄鱼

shell 脚本使用合集

最近写了个打印日志的shell 记录一下;

#!/bin/bash
# 涵盖大部分使用场景
# 1. 基础配置与颜色配置(提升可读性)
# 定义颜色变量,方便后续输出高亮信息
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color (重置颜色)

# 开启严格模式 (最佳实践:遇到错误立即停止,防止错误扩散)
set -euo pipefail

# 定义日志函数
log_info()    { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warn()    { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error()   { echo -e "${RED}[ERROR]${NC} $1"; }

# ------------------------------------------------------------------------------
# 2. 变量与数据类型
# ------------------------------------------------------------------------------
demo_variables() {
    log_info ">>> 进入模块:变量与字符串操作"

    # 定义变量 (注意:等号两边不能有空格)
    local name="ShellMaster"
    local version=1.0
    local is_active=true

    # 字符串拼接
    local greeting="Hello, ${name}!"
    
    # 获取命令执行结果 (命令替换)
    local current_date=$(date +%Y-%m-%d)
    local current_dir=$(pwd)

    # 数组的使用
    local fruits=("Apple" "Banana" "Cherry")

    echo "--------------------------"
    echo "问候语: $greeting"
    echo "日期: $current_date"
    echo "当前目录: $current_dir"
    echo "数组第二个元素: ${fruits[1]}" # 数组索引从0开始
    echo "数组所有元素: ${fruits[@]}"
    echo "--------------------------"
}

# ------------------------------------------------------------------------------
# 3. 参数解析 (处理命令行参数)
# ------------------------------------------------------------------------------
demo_arguments() {
    log_info ">>> 进入模块:参数解析"
    
    # 这是一个演示函数,实际运行时通过 ./script.sh -u user -v 调用
    # 使用 getopts 处理标准参数 (-u username -v -h)
    
    local username=""
    local verbose=false

    # 重置 getopts 索引
    OPTIND=1 

    # h: help, u: user (需要参数), v: verbose (不需要参数)
    while getopts "h?u:v" opt; do
        case "$opt" in
        h|\?)
            echo "用法: $0 [-u 用户名] [-v]"
            return 0
            ;;
        u)  username=$OPTARG
            ;;
        v)  verbose=true
            ;;
        esac
    done

    # 偏移参数,让 $1 指向非选项参数
    shift $((OPTIND-1))

    if [ -n "$username" ]; then
        log_success "指定用户: $username"
    else
        log_warn "未指定用户,使用默认用户"
    fi

    if [ "$verbose" = true ]; then
        log_info "详细模式已开启"
    fi
}

# ------------------------------------------------------------------------------
# 4. 流程控制 (If/Case)
# ------------------------------------------------------------------------------
demo_conditions() {
    log_info ">>> 进入模块:条件判断"

    local score=85

    # If-Else 结构
    if [ "$score" -ge 90 ]; then
        log_success "等级: A (优秀)"
    elif [ "$score" -ge 80 ]; then
        log_info "等级: B (良好)"
    elif [ "$score" -ge 60 ]; then
        log_warn "等级: C (及格)"
    else
        log_error "等级: D (不及格)"
    fi

    # 文件判断 (常见场景)
    local test_file="./test_temp.txt"
    
    # 创建临时文件用于测试
    touch "$test_file"

    if [ -f "$test_file" ]; then
        log_success "文件 $test_file 存在且是普通文件"
    fi

    if [ ! -d "$test_file" ]; then
        log_info "$test_file 不是一个目录"
    fi

    # 清理测试文件
    rm "$test_file"

    # Case 结构 (类似于 Switch)
    local os_type=$(uname -s)
    case "$os_type" in
        Linux)
            log_info "操作系统: Linux"
            ;;
        Darwin)
            log_info "操作系统: macOS"
            ;;
        *)
            log_warn "操作系统: 其他 ($os_type)"
            ;;
    esac
}

# ------------------------------------------------------------------------------
# 5. 循环结构 (For/While)
# ------------------------------------------------------------------------------
demo_loops() {
    log_info ">>> 进入模块:循环结构"

    # C语言风格的 For 循环
    log_info "--- C风格 For 循环 ---"
    for ((i=1; i<=3; i++)); do
        echo "计数: $i"
    done

    # 遍历列表/数组
    log_info "--- 遍历数组 ---"
    local servers=("Web" "DB" "Cache")
    for server in "${servers[@]}"; do
        echo "正在检查服务: $server ..."
        # sleep 0.1 # 模拟耗时操作
    done

    # While 循环 (读取文件或持续监控)
    log_info "--- While 循环 ---"
    local count=1
    while [ $count -le 3 ]; do
        echo "While 循环次数: $count"
        ((count