Skip to content

Shell 技巧

  • 使用 find | xargs -P 的方式进行并行时,推荐 find -print0 | xargs -0 -P 的方式,使用 Null\0)作为分隔符,会更加鲁棒。
    • Null 是唯一不能在文件名中使用的字符。
  • 使用数组动态构建参数,要比使用字符串动态构建方便且安全。
  • head -n 8 example.yaml > example.yamlhead -n 8 example.yaml | tee example.yaml工作的。
    • 前者是因为重定向到同一个文件,会导致文件被清空:shell 会先创建/清空目标文件,然后执行 head 命令。
    • 后者是因为 tee 会立即清空目标文件
    • 解决方案:
      • head -n 8 example.yaml | sponge example.yaml(需要安装 sponge
      • sed -i '9,$d' example.yaml(直接从第 9 行开始删除)
      • 使用临时文件
  • !() 用来匹配某些候选项(例如文件)以外的其他候选项。