Shell 脚本,带名字的参数

shell 脚本,带名字的参数

参考: bash - Passing named arguments to shell scripts - Unix & Linux Stack Exchange

From 3.5.3 Shell Parameter Expansion of the GNU Bash manual:

${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

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
#!/usr/bin/env bash

while [ $# -gt 0 ]; do
case "$1" in
-p|-p_out|--p_out)
p_out="$2"
;;
-a|-arg_1|--arg_1)
arg_1="$2"
;;
*)
printf "***************************\n"
printf "* Error: Invalid argument.*\n"
printf "***************************\n"
exit 1
esac
shift
shift
done

echo "Without default values:"
echo "p_out: ${p_out}"
echo "arg_1: ${arg_1}"
echo
echo "With default values:"
echo "p_out: ${p_out:-\"27\"}"
echo "arg_1: ${arg_1:-\"smarties cereal\"}"

调用方式

1
2
3
$ ./my-script.sh -a "lofa" -p "miez"
$ ./my-script.sh -arg_1 "lofa" --p_out "miez"
$ ./my-script.sh --arg_1 "lofa" -p "miez"

Shell 脚本,带名字的参数
https://yxibng.github.io/2022/02/25/Shell/2022-03-09-shell 脚本,带名字的参数/
作者
yxibng
发布于
2022年2月25日
许可协议