终端命令使用Tips - ShenYj/ShenYj.github.io GitHub Wiki

终端命令使用Tips

随着技术栈不断的扩展,会接触越来越多的终端指令,众多中断指令有很多相似之处,同时也存在不同之处

  • 学会使用帮助文档

    • man xxx
    • xxx --help/xxx -h

      也有特例,比如carthage是使用 carthage help

  • 搜索、查看参数说明

    • 在输出帮助文档后
      • / + 关键字,进行搜索
      • n 键进行下一个匹配
      • shift + n键 向上匹配
      • q 退出
  • 阅读源码

    objdumpnmclang这些工具,都可以通过llvm-project源码进行阅读

快捷键

快捷键 描述
Ctrl + k 删除从光标到行尾
Ctrl + u 删除从光标到行首
Ctrl + w 从光标向前一个单词剪切到剪贴板
Alt + d 从光标向后删除一个单词
Ctrl + d 删除光标下一个字母
Ctrl + h 删除光标前一个字母
Alt + t swap(当前单词,上一个单词)
Ctrl + t swap (当前字母,上一个字母)
Ctrl + y 粘贴上一次删除的文本
Alt + c 大写当前字母,并移动光标到单词尾
Alt + u 大写从当前光标到单词尾
Alt + i 小写从当前光标到单词尾
Ctrl + r 向后搜索历史命令
Ctrl + g 退出搜索
Ctrl + p 历史中上一个命令
Ctrl + n 历史中下一个命令
Alt + . 上一个命令的最后一个单词
Ctrl + i 根据输入的关键字可以匹配相关的命令 (记不准命令和参数的时候很有用)
Ctrl + k 清屏
Ctrl + z 挂起当前命令
Ctrl + q 继续输出
Ctrl + c 停止当前命令
Ctrl + a 移动光标到行首
Ctrl + e 移动光标到行尾
Ctrl + b 相当于 ←
Ctrl + f 相当于 →
!! 重复上一条命令,并不会执行,只是会显示出上一条命令

grep

  • 在进行关键字匹配时,可以根据需要增加-A-B参数来提高效率

    例如 otool -l test | grep 'ID'这段命令

    ❯ otool -l test | grep 'ID' -A 5 -B 5
    Load command 8
              cmd LC_LOAD_DYLINKER
          cmdsize 32
            name /usr/lib/dyld (offset 12)
    Load command 9
        cmd LC_UUID
    cmdsize 24
        uuid 4C4A98DB-0DC0-36CA-9946-1ED05CB4961B
    Load command 10
          cmd LC_BUILD_VERSION
      cmdsize 32
    
    • -A: 向下查找指定行数
    • -B: 向上查找指定行数
    • -m: 匹配的个数限制
  • 默认情况下大小写敏感,如果不希望大小写铭感,可以使用-i

    e.g. otool -l test | grep 'ID' -i

异常处理

在学习开源库时经常会遇到很多脚本,总能看到开头处带有 set -euo pipefail 等类似命令,这是一种异常处理,以 CocoaPods默认生成的脚本为例

set -e 
set -u 
set -o pipefail
  • set -u:
    执行脚本的时候,如果遇到不存在的变量,Bash 默认忽略它, set -u 就用来改变这种行为。脚本在头部加上它,遇到不存在的变量就会报错,并停止执行
  • set -e:
    如果脚本里面有运行失败的命令(返回值非0),Bash 默认会继续执行后面的命令, set -e 它使得脚本只要发生错误,就终止执行 是一种异常处理最简单的处理方式
  • set -o pipefail:
    set -e有一个例外情况,就是不适用于管道命令。 所谓管道命令,就是多个子命令通过管道运算符(|)组合成为一个大的命令。Bash 会把最后一个子命令的返回值,作为整个命令的返回值。也就是说,只要最后一个子命令不失败,管道命令总是会执行成功,因此它后面命令依然会执行,set -e就失效了 set -o pipefail用来解决这种情况,只要一个子命令失败,整个管道命令就失败,脚本就会终止执行

参考资料

  • set -u/set -o nounset、set -e、 set -o pipefail

  • Circle官方文档中有详细说明

    -o pipefail

    If make test fails, the -o pipefail option will cause the whole step to fail. Without -o pipefail, the step will always run successfully because the result of the whole pipeline is determined by the last command (tee test-output.log), which will always return a zero status.
    
    Note that even if make test fails the rest of pipeline will be executed.
    
    If you want to avoid this behaviour, you can specify set +o pipefail in the command or override the whole shell (see example above).
    
    In general, we recommend using the default options (-eo pipefail) because they show errors in intermediate commands and simplify debugging job failures. For convenience, the UI displays the used shell and all active options for each run step.
    
⚠️ **GitHub.com Fallback** ⚠️