linux - 在 linux 中使用 while 循环一个一个地测试函数参数

标签 linux bash shell sh

我正在编写一个脚本,我应该在其中测试用户通过使用 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/

相关文章:

bash - 在 sed 的替换字符串中使用文件内容

linux - 使用shell脚本自动化scp网站文件传输

bash - docker上的Nginx-守护并附加到bash

c - 如何在 C 中多次调用 sem_open?

bash 4.x assoc 数组在接收函数中丢失键

linux - "zip -m"目录变空不删除

linux - 想知道脚本结果的 pid

regex - 使用 sed 更改文件扩展名

linux - 恢复 Snow Leopard 上文档的符号链接(symbolic link)

linux - rtnetlink (Linux) 中的 IFA_LOCAL 和 IFA_ADDRESS 有什么区别