Bash 常用语法与命令速查

常用命令

set -euo pipefail
set -x
bash -n script.sh
shellcheck script.sh

name="app"
echo "${name}"
read -r -p 'Continue? ' answer
printf '%s\n' "$name"

if [[ -f "$file" && "$name" == app* ]]; then
  echo ok
elif [[ ! -d "$dir" ]]; then
  echo missing
fi

for f in *.log; do
  echo "$f"
done

while IFS= read -r line; do
  echo "$line"
done < input.txt

case "$1" in
  start) echo start ;;
  stop)  echo stop ;;
  *)     echo usage; exit 1 ;;
esac

greet() {
  local who="${1:-world}"
  echo "hello $who"
}

场景速查

目的 写法
默认值 ${var:-default}
必填检查 ${var:?missing}
去后缀 ${file%.log}
去前缀 ${path#*/}
数组 arr=(a b c); echo "${arr[@]}"
关联数组 declare -A m; m[k]=v
命令替换 out=$(cmd)
进程替换 diff <(cmd1) <(cmd2)
重定向 stderr cmd 2>err.log
同时看输出和保存 `cmd
超时 timeout 10 cmd

易错点

相关命令