我正在编写一个脚本,我应该在其中测试用户通过使用 while 循环提供的参数。最后一个参数应该始终是“本地的”,参数计数没有固定的数量(我们可以添加任意数量的参数)
到目前为止,这是我的代码:
#!/bin/sh
echo
echo -n 'My OS is : '
unamestr=`uname`
echo $unamestr
i=1
while [ "${@:i}" != "local" ]
do
if [ "${@:i}" == "mysql" ]
then
#add the repository
wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
sudo rpm -ivh mysql-community-release-el7-5.noarch.rpm
yum update
#Install mysql
sudo yum install mysql-server
sudo systemctl start mysqld
elif [ "${@:i}" == "chrome" ]
then
echo 'Installing Chrome'
else
echo 'Nothing'
fi
let i++
done
为了测试所有参数,我需要知道 while 条件应该是什么。
最佳答案
如果你想使用切片符号索引到$@
, 请注意 "${@:i}"
获取从位置i
开始的所有位置参数.你需要 "${@:i:1}"
只拿一个。要遍历所有这些,请从 $#
中获取计数,所以像这样:
#!/bin/bash
i=1
while (( i <= $# )) ; do
arg=${@:i:1}
if [ "$arg" = that ] ; then
...
fi
let i++
done
请注意,几乎所有这些( let
、 ((...))
、 ==
和 [ .. ]
以及切片符号 ${var:n:m}
)都是 POSIX shell 语言的扩展,因此 hashbang 应该可能表示其他一些 shell ,就像 Bash。
正如 Inian 在另一个答案中展示的那样,通常的 POSIX 方法遍历所有 位置参数是
for arg in "$@" ; do...
或
for arg do ...
如果你需要POSIXly使用当前索引,做类似的事情
i=1
for arg do
if [ "$#" -eq "$i" ] ; then echo "the last one" ; fi
echo "$i: $arg"
i=$(( i + 1 ))
done
关于linux - 在 linux 中使用 while 循环一个一个地测试函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43994902/