Bash Script
References 手册 - Bash Reference Manual 检查工具 - shellcheck Shebang #!/bin/bash # 在 shebang 行中使用 env 命令 #!/usr/bin/env python Variables # 定义变量 var="a string" #等号两边不能有空格 #调用变量 echo $var echo ${var} # `""` suppress expansions except parameter expansion, arithmetic expansion, and command substitution echo "$var" # 双引号会渲染变量,输出`a string` # `''` suppress all expansions echo '$var' # 单引号不会渲染变量,输出`$var` # Arithmetic Expansion echo $((1+1)) # 输出`2` echo $((1.0/2)) # 输出`0.5` # Command Substitution # 执行命令并将输出替换原来内容 `cat some.txt` $( cat some.txt ) # Process Substitution # 执行命令并将输出写到一个临时文件中,并用临时文件名替换原来内容 # 在我们希望返回值通过文件而不是STDIN传递时很有用 diff <(ls foo) <(ls bar) #显示文件夹`foo`和`bar`中文件的区别 # Globbing 通配符 # `?`匹配一个字符,`*`匹配任意个字符 rm foo* # Brace Expansion # 花括号展开 echo Number_{1..5} echo Front-{A,B,C}-Back Positional Paramaters $0:路径 dirname $0:路径名 basename $0:文件名 $1~$9:输入参数 $@: 所有参数,$*:区别是会展开双引号中的参数 $#: 参数个数 $?:上一次退出状态,0为正常,其他为错误 $$: 当前脚本的进程识别码 Logit Expression Logit [[ exp1 && exp2 ]] and [[ exp1 || exp2 ]] or [[ ! exp1 ]] not # do command2 if command1 is sucessful command1 && command2 # do command2 if command1 is unsucessful command1 || command2 Function function func { commands return } # or func () { commands return } # local variable function func { local var var=2 return } # function arguments func () { echo "Parameter #1 is $1" # arguments are refered by position } func "$arg1" "$arg2" # call function with arguments Branching and Looping If x=5 if [[ $x -eq 5 ]]; then echo "x equals 5." elif [[ $x -eq 4 ]]; then echo "x equals 4." else echo "x does not equal 5 or 4." fi Case read -p case $REPLY in 0) echo "zero" ;; 1) echo "one" ;; 2) echo "two" ;; *) echo "other" ;; esac While count=1 while [[ $count -le 5 ]]; do echo $count count=$((count + 1)) done while true; do echo 1 sleep 1 done For for (( i=0; i<5; i=i+1 )); do echo $i done for i in {1..100}; do echo $i done # iterate arguments from the 3rd for i in "${@:3}"; do echo $i done Test test 手册 ...