如何检查 args 从 bash 中的"--"开始



以下bash脚本无法检查变量是否以"--";。

下面是test.sh:

#!/bin/bash
echo -e "Args: [$@]"
if [[ "${$@:0:2}" == "--" ]]
then
echo -e "Args starts with --: [$@]"
else
echo -e "Args does not start with --: [$@]"
fi

下面是测试:

./test.sh "--hello --many --args --here --must --starts --with"
./test.sh "world"

输出如下:

root@test:~# ./test.sh "--hello"
Args: [--hello --many --args --here --must --starts --with]
./test.sh: line 5: ${$@:0:2}: bad substitution
root@test:~# ./test.sh "world"
Args: [world]
./test.sh: line 5: ${$@:0:2}: bad substitution
root@test:~# 

上面脚本中的问题是什么,如何修复?

${$@}无效(与${$x}相同),应为${@};但是我不认为从这个特殊的(数组?)变量中取子字符串是有意义的。


相反,您可以使用循环和case语句来检查模式的位置参数。这甚至可以用sh,而不仅仅是bash

#!/bin/sh
for param; do
echo "Checking positional parameter '$param'"
case "$param" in
--*) echo "Param '$param' starts with double-hyphen"
;;
*) echo "Param '$param' does not start with double-hyphen"
;;
esac
done

输出:

$ ./test.sh "--hello --many --args --here --must --starts --with";
Checking positional parameter '--hello --many --args --here --must --starts --with'
Param '--hello --many --args --here --must --starts --with' starts with double-hyphen
$ ./test.sh "world"
Checking positional parameter 'world'
Param 'world' does not start with double-hyphen
$ ./test.sh -a -n 5 --verbose
Checking positional parameter '-a'
Param '-a' does not start with double-hyphen
Checking positional parameter '-n'
Param '-n' does not start with double-hyphen
Checking positional parameter '5'
Param '5' does not start with double-hyphen
Checking positional parameter '--verbose'
Param '--verbose' starts with double-hyphen
$ ./test.sh '-a -n 5 --verbose'
Checking positional parameter '-a -n 5 --verbose'
Param '-a -n 5 --verbose' does not start with double-hyphen

NB引号内的参数算作单个参数。如果您需要多个单独的参数,则不能引用它们。

最新更新