文章

shell 脚本零食铺

隐藏指令输出

如果想让终端不打印某条指令的运行结果,可以使用:

1
command > /dev/null 2>&1

解决引入另一个脚本后,在其他路径执行脚本报错的问题

脚本 A 引入了脚本 B 和 C。如果不在脚本 A 所在的路径执行脚本 A,那么终端会因为找不到 B 和 C 而报错:CommonEcho.sh: No such file or directory

比较好的解决方案是在引入脚本 B 和 C的时候指明它们的路径(但不是写死路径):

1
2
source $(dirname "$0")/lib_example
source $(dirname "$0")/xxx.sh

如果脚本 B/C 在脚本 A 的父级目录里面,则可以通过套娃的方式:

1
2
source $(dirname "$(dirname "$0")")/B.sh
source $(dirname "$(dirname "$0")")/C.sh

参考:https://www.baeldung.com/linux/source-include-files

处理长命名参数

以空格区分参数和参数值

参考链接:https://stackoverflow.com/a/14203146/16991379

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
POSITIONAL_ARGS=()

while [[ $# -gt 0 ]]; do
  case $1 in
    -e|--extension)
      EXTENSION="$2"
      shift # past argument
      shift # past value
      ;;
    -s|--searchpath)
      SEARCHPATH="$2"
      shift # past argument
      shift # past value
      ;;
    --default)
      DEFAULT=YES
      shift # past argument
      ;;
    -*)
      echo "Unknown option $1"
      exit 1
      ;;
    *)
      POSITIONAL_ARGS+=("$1") # save positional arg
      shift # past argument
      ;;
  esac
done

以等号区分参数和参数值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for i in "$@"; do
  case $i in
    -e=*|--extension=*)
      EXTENSION="${i#*=}"
      shift # past argument=value
      ;;
    -s=*|--searchpath=*)
      SEARCHPATH="${i#*=}"
      shift # past argument=value
      ;;
    --default)
      DEFAULT=YES
      shift # past argument with no value
      ;;
    -*|--*)
      echo "Unknown option $i"
      exit 1
      ;;
    *)
      ;;
  esac
done

比较大小

参数运算符

1
2
3
4
5
6
-eq # Equal
-ne # Not equal
-lt # Less than
-le # Less than or equal
-gt # Greater than
-ge # Greater than or equal
1
2
3
4
5
6
7
8
#!/bin/bash

a=2462620
b=2462620

if [ "$a" -eq "$b" ]; then
  echo "They're equal";
fi

或者直接用数学运算符

1
2
3
if (( a > b )); then
    ...
fi
本文由作者按照 CC BY-NC-SA 4.0 进行授权