Bash 脚本参数传递分三种方式:位置参数(简单固定)、带选项参数(灵活推荐)、getopts 短选项(简洁)。
位置参数
适合参数固定、顺序明确的场景,通过 $1、$2 直接获取。
| 变量 | 含义 |
|---|
$0 | 脚本文件名 |
$1, $2 | 第 1、2 个参数 |
$# | 参数个数 |
$@ | 所有参数(独立) |
$? | 上一命令退出状态 |
示例:
1
2
3
4
5
6
7
8
| #!/bin/bash
if [ $# -ne 2 ]; then
echo "用法:bash $0 <路径> <数量>"
exit 1
fi
input_path=$1
count=$2
echo "路径:$input_path,数量:$count"
|
运行:bash script.sh ./data 3
带选项参数(推荐)
支持长选项、任意顺序、默认值、可选参数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| #!/bin/bash
input_path="./default"
count=1
while [[ $# -gt 0 ]]; do
case "$1" in
--input) input_path="$2"; shift 2 ;;
--count) count="$2"; shift 2 ;;
--help) echo "用法:$0 [--input 路径] [--count 数量]"; exit 0 ;;
*) echo "未知选项:$1"; exit 1 ;;
esac
done
echo "路径:$input_path,数量:$count"
|
运行:
bash script.sh(使用默认值)bash script.sh --input ./data --count 3bash script.sh --count 3 --input ./data(顺序不限)
getopts 短选项
语法简洁,仅支持单字符选项。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| #!/bin/bash
input_path="./default"
count=1
while getopts "i:c:h" opt; do
case "$opt" in
i) input_path="$OPTARG" ;;
c) count="$OPTARG" ;;
h) echo "用法:$0 [-i 路径] [-c 数量]"; exit 0 ;;
?) echo "无效选项"; exit 1 ;;
esac
done
echo "路径:$input_path,数量:$count"
|
运行:bash script.sh -i ./data -c 3
对比选择
| 方式 | 优点 | 缺点 | 适用场景 |
|---|
| 位置参数 | 最简单 | 顺序固定 | 1-2 个参数 |
| 带选项参数 | 灵活、支持长选项 | 代码较长 | 大多数场景 |
| getopts | 简洁 | 不支持长选项 | 需要短选项 |
实用技巧
参数带空格:用引号包裹,脚本中也用引号 "$var"
参数校验:
1
2
3
4
5
6
7
8
9
| # 校验正整数
if ! [[ $count =~ ^[1-9][0-9]*$ ]]; then
echo "数量必须是正整数"; exit 1
fi
# 校验路径存在
if [ ! -d "$input_path" ]; then
echo "路径不存在"; exit 1
fi
|
Comments