Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在linux中使用while循环逐个测试函数参数_Linux_Bash_Shell_Sh - Fatal编程技术网

在linux中使用while循环逐个测试函数参数

在linux中使用while循环逐个测试函数参数,linux,bash,shell,sh,Linux,Bash,Shell,Sh,我正在编写一个脚本,在这个脚本中,我应该使用while循环测试用户给出的参数。最后一个参数应始终为“local”,并且参数计数没有固定数量(我们可以添加任意数量的参数) 以下是我目前的代码: #!/bin/sh echo echo -n 'My OS is : ' unamestr=`uname` echo $unamestr i=1 while [ "${@:i}" != "local" ] do if [ "${@:i}" == "mysql" ] then

我正在编写一个脚本,在这个脚本中,我应该使用while循环测试用户给出的参数。最后一个参数应始终为“local”,并且参数计数没有固定数量(我们可以添加任意数量的参数)

以下是我目前的代码:

#!/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条件应该是什么,以便测试所有参数。

这个想法是正确的,只需使用适当的循环来循环所有输入参数。将其用作外部循环,并在内部进行检查

for arg in "$@"; do

    # Proceed to next argument if the current is "local"
    [ "$arg" = "local" ] && continue

    if [ "$arg" = "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 [ "$arg" = "chrome" ]
    then
        echo 'Installing Chrome'
    else
        echo 'Nothing'
    fi
done

这应该与您的
POSIX
shell
sh
兼容

如果要使用切片表示法索引到
$@
,请注意
“${@:i}”
将获取从位置
i
开始的所有位置参数。您需要
“${@:i:1}”
才能只取一个。要运行所有这些,请从
$#
获取计数,如下所示:

#!/bin/bash
i=1
while (( i <= $# )) ; do
    arg=${@:i:1}
    if [ "$arg" = that ] ; then
         ...
    fi
    let i++
done

如果需要精确地使用当前索引,请执行以下操作

i=1
for arg do
    if [ "$#" -eq "$i" ] ; then echo "the last one" ; fi
    echo "$i: $arg"
    i=$(( i + 1 ))
done

我找不到你的答案@这解决了我的问题!!谢谢,很抱歉耽搁了你
for arg do ...
i=1
for arg do
    if [ "$#" -eq "$i" ] ; then echo "the last one" ; fi
    echo "$i: $arg"
    i=$(( i + 1 ))
done