curl执行bash脚本如何在管道后追加参数

1.传递单个参数

1.1 init

1
curl -sSL https://xxxx/ops/monitor/auto.sh | bash -s -- init

1.2 update

1
curl -sSL https://xxx/ops/monitor/auto.sh | bash -s -- update

2.参数原理

这里:

1
bash -s -- init

含义:

参数 作用
-s 让 bash 从 stdin 读取脚本
-- 表示后面不再是 bash 自身参数
init 传递给脚本的 $1

因此脚本内:

1
echo $1

会输出:

1
init

3.auto.sh 内部处理示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env bash

ACTION="$1"

case "$ACTION" in
init)
echo "执行初始化"
;;
update)
echo "执行更新"
;;
*)
echo "Usage: $0 {init|update}"
exit 1
;;
esac

4.多个参数传递

例如:

1
curl -sSL xxx/auto.sh | bash -s -- init prod v1

脚本中:

1
2
3
$1 -> init
$2 -> prod
$3 -> v1

5.生产环境更安全的方式

不建议直接 pipe 到 bash。

更推荐:

1
2
3
4
5
curl -fsSLO https://xxx/ops/monitor/auto.sh

chmod +x auto.sh

./auto.sh init

优点:

  • 可审计
  • 可缓存
  • 可校验 hash
  • 可断点排障
  • 避免 MITM 风险
  • 避免下载失败执行残缺脚本