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"
|