Bash 在参数名称中使用变量值
我正在编写一个bash脚本,它将输入参数,命令如下所示:Bash 在参数名称中使用变量值,bash,Bash,我正在编写一个bash脚本,它将输入参数,命令如下所示: command -a -b -c file -d -e 我想检测一个特定的参数-b,其具体位置为$1、$2、$3 #! /bin/bash counter=0 while [ counter -lt $# ] do if [ $($counter) == "-b" ] then found=$counter fi let counter+=1 done 问题出现在$$计数器中。有没有一种
command -a -b -c file -d -e
我想检测一个特定的参数-b,其具体位置为$1、$2、$3
#! /bin/bash
counter=0
while [ counter -lt $# ]
do
if [ $($counter) == "-b" ]
then
found=$counter
fi
let counter+=1
done
问题出现在$$计数器中。有没有一种方法可以使用$counter调用参数的值?例如,如果counter=2,我想调用参数$2的值$$计数器不工作。您可以在不使用getopts的情况下完成此操作,但仍然推荐使用getopts,不过可以通过修改循环来完成
counter=1
for i in "$@"; do
if [[ $i == -b ]]; then
break
fi
((counter+=1))
done
只需直接迭代参数,而不是迭代参数位置
bash还允许使用以下语法进行间接参数扩展:
#! /bin/bash
counter=0
while [ counter -lt $# ]
do
if [ ${!counter} = "-b" ] # ${!x} uses the value of x as the parameter name
then
found=$counter
fi
let counter+=1
done
为此使用getopts。例如,我可以帮忙。好的,谢谢!我会研究它,但是如果我想要下面的文件名,例如-b filename,getopts也提供这个函数吗?是的。您看过吗?不要将==与单括号符号一起使用,bash接受它,但它不符合POSIX,其他shell也会被它阻塞+剩下的1个!非POSIX shell可能会在${!counter}上阻塞:但您通常是正确的。