deepwzh的技术笔记
  • Golang
  • Python
  • Cpp
杂项
前端开发
  • 计算机网络
  • 操作系统
  • 数据库
云原生
Devops
AIGC
关于作者
  • Golang
  • Python
  • Cpp
杂项
前端开发
  • 计算机网络
  • 操作系统
  • 数据库
云原生
Devops
AIGC
关于作者
  • 操作系统
  • Linux 源码阅读笔记
  • 内存管理
  • 文件系统
  • Windows

    • Windows
    • 端口转发
    • WSL

      • WSL
      • 与 windows 的互通
      • 安装
      • wsl 常见问题
      • 在 wsl 下进行开发
      • 配置
  • Linux

    • Linux
    • 动态追踪技术
    • DNS 配置
    • 问题排查
    • 杂项
    • Linux 免密登录
    • ebpf
    • 性能调优
    • init 进程
    • Ipvs
    • 基准测试
    • Linux
    • Keepalived
    • Linux 与 Unix
    • 系统调用
    • 命令行补全
    • 文件系统

      • 文件系统
      • Mount
    • systemd

      • systemd
      • Systemd
    • 命令工具

      • 命令工具
      • 时区配置
      • 进程管理工具
      • 路由表维护
      • 文件系统工具
      • 网络工具

        • 网络工具
        • curl
        • 端口转发 rinetd
    • 包管理

      • 包管理
      • APT 与 DEB
    • Shell

      • Shell
      • Zsh
      • Bash

        • Bash
        • 配置文件

Bash

命令

set 命令

set -o pipefail :在 Bash 中,管道(|)默认仅以最后一个命令的退出状态作为整个管道的返回值,开启这个选项后,管道中任意一个命令失败都会导致整个管道返回非 0 状态码。

set -e :任意命令出错都会导致退出

并行执行

for arg in "aa bb"
  ./program & # 在子进程中执行
fi
wait # 等待所有子进程执行完

条件判断

[ 与[[

  • [ 是 test 命令
  • [[ 是 Bash 的扩展测试命令,提供了更强大的功能

逻辑运算符

在 Bash 中,运算符的优先级如下:

  1. 逻辑运算符:

    • !(逻辑非)
    • &&(逻辑与)
    • ||(逻辑或)
  2. 比较运算符:

    • eq, ne, lt, le, gt, ge(数字比较)
    • =, !=, <, >(字符串比较)

可以使用括号指定优先级

if [[ "$a" -lt "$b" && "$b" -gt 15 ]]; then
    echo "Both conditions are true: a is less than b and b is greater than 15."
fi

if [[ ("$a" -lt "$b") && ("$b" -gt 15) ]]; then
    echo "Both conditions are true."
fi

字符串匹配

== 用于相等关系的判断

if [[ "$string" == _substring_ ]]; then
    echo "Contains substring"
fi

=~ 则用于正则关系匹配

if [[ "$string" =~ pattern ]]; then
        echo "Matches regex"
fi

其中 pattern 是用正则表达式的语法的模式串

比较

相等

if [[ "$str1" == "$str2" ]]; then
    echo "Strings are equal"
fi
if [ "$str1" = "$str2" ]; then
    echo "Strings are equal"
fi

字典序大小比较

if [[ "$str1" < "$str2" ]]; then
    echo "$str1 comes before $str2"
fi
if [[ "$str1" > "$str2" ]]; then
    echo "$str1 comes after $str2"
fi

不等

if [[ "$str1" != "$str2" ]]; then
    echo "Strings are not equal"
fi

空非空字符串检查

if [[ -z "$str1" ]]; then
    echo "String is empty"
fi
if [[ -n "$str1" ]]; then
    echo "String is not empty"
fi

数字比较

if [ "$num1" -eq "$num2" ]; then
    echo "Numbers are equal"
fi
if [ "$num1" -ne "$num2" ]; then
    echo "Numbers are not equal"
fi
if [ "$num1" -gt "$num2" ]; then
    echo "$num1 is greater than $num2"
fi
if [ "$num1" -lt "$num2" ]; then
    echo "$num1 is less than $num2"
fi
if [ "$num1" -le "$num2" ]; then
    echo "$num1 is less than or equal to $num2"
fi

注意事项

  • 最好都加引号,防止解析出错
  • 使用[时,必须在括号和条件之间添加空格。
  • [[支持逻辑运算符&&和 ||, [则不支持
  • [[ 允许使用模式匹配(如 == 和 !=),支持通配符 * 和 ?, [判断相等得用=
  • 使用 [[ 时,如果变量未定义,返回空字符串不会导致错误。使用 [ 时,如果未定义变量,会导致错误

子文档

  • 配置文件
Next
配置文件