Bash 笔记
Table of Contents
基本
- 基本语法介绍: Bash scripting cheatsheet, 推荐 熟读 或 随手查阅.
- 进阶书籍: Pure Bash Bible, 真·大佬出品.
- 脚本参数设计: Command-line interface description language
- 代码分析工具: ShellCheck
小提示
- 使用变量时, 一定要用引号. 如:
echo "$var"
- 声明函数时, 无需使用关键字
function
- 执行命令时, 用
$()
代替` `
. 如:var="$(command "$(command)")"
MacOS
MacOS 与 Linux 在很多命令存在不兼容的问题. 可以在脚本最前加上以下代码.
需要依赖: coreutils (brew install coreutils
)
[[ $(uname) == "Darwin" ]] && PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
字符串操作
常用操作
str="foo.bar" echo ${str%%.*} # => foo (文件名) echo ${str//*.} # => bar (文件扩展名)
- 删除和替换
${FOO%suffix} | Remove suffix |
${FOO#prefix} | Remove prefix |
${FOO%%suffix} | Remove long suffix |
${FOO##prefix} | Remove long prefix |
${FOO/from/to} | Replace first match |
${FOO//from/to} | Replace all |
${FOO/%from/to} | Replace suffix |
${FOO/#from/to} | Replace prefix |
- 截取
${FOO:0:3} | Substring(position, length) |
${FOO:-3:3} | Substring from the right |
- 其他
${#FOO} | Length of $FOO |
${FOO:=val} | Set $FOO to val if not set |
${FOO:-val} | val if $FOO is not set |
${FOO:+val} | val if $FOO is set |
${FOO,} | lowercase 1st letter |
${FOO,,} | all lowercase |
${FOO^} | uppercase 1st letter |
${FOO^^} | all uppercase |
不常用命令备忘
# Print value of a symbolic link or canonical file name readlink --help
代码片段
下面保存一些常用的代码, 提高开发效率;)
最小代码模板
#!/usr/bin/env bash main() { ... } main "$@"
获取脚本的目录信息
# 脚本真实链接 script_link="$(readlink -f "$0")" printf '%s\n' "$script_link" # 脚本所在目录 script_dir="$(dirname "$(readlink -f "$0")")" printf '%s\n' "$script_dir" # 脚本文件名 script_file="$(basename "$(readlink -f "$0")")" printf '%s\n' "$script_file"
从命令声明数组
read -d "" -ra a1 <<< "$(seq 1 5)" echo "${a1[@]}" # output: # 1 2 3 4 5 a2=("$(seq 1 5)") echo "${a2[@]}" # output: # 1 # 2 # 3 # 4 # 5
遍历文件的行
while read -r line; do printf '%s\n' "$line" done < "file" cat "file" | while read -r line; do printf '%s\n' "$line" done
遍历文件和目录
for file in *; do printf '%s\n' "$file" done
输出带颜色的文字
# 输出所有颜色(from: http://jafrog.com/2013/11/23/colors-in-terminal.html) for code in {0..255}; do echo -e "\e[38;5;${code}m"'\\e[38;5;'"$code"m"\e[0m" done # 随机一个颜色 echo -e "\e[38;5;$((RANDOM%256))m#######\e[0m"
切换用户执行
su <other_user> << ! ... exit !