Shell Skills

基础知识

shebang 字符

  • 在 Bash 中,每个命令都是通过分号或换行符来分隔的
  • 当使用 bash shell.sh 运行脚本时不需要
  • 当使用 ./shell.sh 运行脚本时,脚本的第一行需要有 #! /bin/bash

终端打印

命令

  • echo
    • -e: 转义序列
    • 颜色:echo -e "\e[1;31m text \e[0m"
  • printf
  • 可以在 echo 和 printf 的双引号中引用变量

三种模式

  • 双引号:推荐使用
  • 单引号
  • 不加引号

环境变量

  • 在 Bash 中,每个变量的值都是字符串
  • export 命令用来设置环境变量
  • 查看进程中的环境变量:cat /proc/$PID/environ
  • 查看某个进程 PID:pgrep appName

赋值与相等

  • 赋值:var=value
  • 相等:var = value

重定向

  • <: 输出到 stdin
  • >: 截断,清除再添加
  • >>: 在末尾添加
  • 命令执行完的退出状态:$?
    • 成功:0
    • 失败:非 0
  • /dev/null 是一个特殊的设备文件,它接收到的任何数据都会被丢弃

调试脚本

  • -x:开启跟踪调试功能
  • set-x 和 set +x 实现对脚本的部分调试

函数和参数

参数

  • $1: 第一个参数
  • $2: 第二个参数
  • $@: 列表展示所有参数
  • $*: 字符串展示所有参数

管道

子 Shell

  • (command): 前缀加 $ 可以赋值给变量
  • `command`: 直接赋值给变量
  • “$(command)”: 可以保留空格和换行符

比较与测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if condition ;
then
command ;
else
command ;
fi

# 逻辑真
[ condition ] && command ;

# 逻辑假
[ condition ] || command ;

# 三元表达式
[ condition ] && command1 : command2 ;

算术比较

  • 条件通常被放置在封闭的中括号内
  • 一定要注意在 [ 或者 ] 与操作数之间有一个空格
  • 操作符
    • -eq
    • -ne
    • -gt
    • -lt
    • -ge
    • -le
    • -a: 逻辑与
    • -o: 逻辑或
    • -f: 存在正常的文件路径
    • -d: 存在目录
    • -e: 存在文件

字符串比较

  • 使用字符串比较时,最好用双中括号
  • 操作符
    • =
    • !=
    • >
    • <
    • -z: 空字符串
    • -n: 非空字符串

用 test 可以避免使用过多的括号

文本操作

find

find path option file

  • -name: 匹配文件名
  • -iname: 不区分大小写
  • \( -name file -o \): 多个条件
  • -path: 匹配路径
  • -regex: 正则表达式
  • -iregex: 不区分大小写
  • !: 否定
  • -maxdepth: 最大深度
  • -mindepth: 最小深度
  • -type: 类型
  • -atime: 访问时间
    • -number: 最近几天
    • +number: 超过
  • -mtime: 修改时间
  • -ctime: 变化时间
  • -newer: 比文件新
  • -delete: 删除
  • -perm: 权限

正则表达式

grep

  • grep pattern filename
  • -E: 使用正则表达式,或者 egrep
  • -o: 只输出匹配部分
  • -v: 反转
  • -c: 统计行数
  • -n: 显示行数
  • -b -o: 偏移
  • -l: 匹配文件
  • -L: 不匹配文件
  • -R -n: 遍历
  • -i: 忽略大小写
  • -e: 指定多个匹配项
  • -q: 静默输出
  • --include
  • --exclude
  • --exclude-dir
  • -A number: 匹配结果前 number 行
  • -B number: 匹配结果后 number 行
  • -C number: 匹配结果前后 number 行

cut

切分列操作
cut -f number1,number2 filename

  • --complement: 不包含该列
  • -d: 指定分隔符

sed

文本替换
sed 's/pattern/replace_string/' file

  • -i: 替换并保存
  • 's/pattern/replace_string/g': 全局替换
  • sed '/^$/d file': 删除空白行
  • $: 已匹配字符串
  • \1: 字串匹配

tr

只能对标准输出进行替换
tr set1 set2

  • tr -d set: 删除字符
  • tr -d -c set: 删除补集字符
  • tr -s ' ': 压缩字符

压缩

gzip

  • gzip 只能压缩单个文件或数据流,而无法对目录和多个文件进行归档
  • 压缩:gzip filename
  • 解压:gunzip filename.gz

rsync 备份数据

  • rsync 命令用 SSH 连接远程主机
  • 不适用于两台远程主机之间互相传送数据

技巧

SSH 免密码登入

  • ssh-copy-id remote-host@ip