Some Bash Trick

1 介绍 本文介绍一些我写 Bash 脚本常用的技巧,帮助我们写一些比较复杂的 Bash 脚本。说句题外话,我个人觉得用 Bash 写脚本还是比 Python 方便,当然用 Python 写更简单,门槛更低。但是 Python 太大了,很多嵌入式系统中根本不适合安装,而 Bash 的话就没有这个问题。从我的经验来说,我觉得嵌入式系统更适合用 Bash,功能也足够强大。 2 通用模块 1 命令行解析 Bash 脚本通常需要通过命令行输入参数,这时候一个好的命令行解析功能就相当重要。这里提供一个可以解析 Option 和 Command 的解析函数。 #! /usr/bin/env bash COMMAND="" # hint for users function show_usage() { cat <<EOF Usage: $0 [options] ... OPTIONS: -h, --help Display this help and exit. -a, --aoption Change it to your option. -b, --boption Change it to your option. acommand Change it to your command....

March 26, 2024 · 1 min · 195 words · Croak

jq example

介绍 当我们想在 Shell 脚本中解析 Json 文件时,我们通常会使用 jq 工具。本文记录一些使用 jq 的方法,基本上可以用来解析所有 Json 的特性。 本篇文章测试 Json 文件 基础用法 解析字段 # 输出 json 格式 jq -c '.value1' < jq_example.json # 输出 raw string jq -r '.value1' < jq_example.json jq -r '.value2.value21' < jq_example.json jq -r '.value2.value22.value221' < jq_example.json 判断字段是否存在 $ jq 'has("value1")' < jq_example.json true $ jq 'has("value10")' < jq_example.json false 进阶用法 解析数组 #! /usr/bin/env bash readarray -t array1 <<<"$(jq -c '.array1[]' < jq_example....

March 20, 2024 · 1 min · 111 words · Croak