How can I test whether a positional parameter is set in Bash?
我想知道为什么无论我是否将第一个位置参数传递给下面的函数,测试
1 2 3 4 5 6 | shopt -os nounset function foo { echo -n"$FUNCNAME: 1st positional parameter" [[ ! -v 1 ]] && echo"is missing." || echo is""$1"." } |
我知道还有其他测试方法,但是为什么这个特定的测试不起作用?
在这种情况下,您要检查参数是否未设置。
1 2 3 4 5 6 7 | has_1() { if [[ -z"${1+present}" ]]; then echo"no first param" else echo"given: $1" fi } |
仅当未设置参数时,参数扩展
Bash 5.1具有非常简单的方法来执行此操作。如发行说明中所述:
x. `test -v N' can now test whether or not positional parameter N is set.
因此要检查是否设置了第N个参数,可以使用以下任一方法:
1 | test -v N |
1 | [ -v N ] |
查看一个非常基本的示例:
1 2 | test -v 1 && echo"1st parameter is set: '$1'" [ -v 2 ] && echo"2nd parameter is set: '$2'" |
查看一些示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 | bash-5.1$ bash script.sh"" 1st parameter is set: '' bash-5.1$ bash script.sh a b 1st parameter is set: 'a' 2nd parameter is set: 'b' bash-5.1$ bash script.sh"" 1st parameter is set: '' bash-5.1$ bash script.sh"" bla 1st parameter is set: '' 2nd parameter is set: 'bla' |
1 | if ["$#" -gt"0" ]; then echo 'ok'; else echo '0'; fi |
以下模式涵盖了大多数实际用例:
1 | [[ -z"${2:-}" ]] && echo"The 2'nd parameter is unset">&2 && exit 1 |
壳参数扩展