簡體   English   中英

麻煩的android bash shell腳本

[英]Trouble with android bash shell script

每當在android上通過調用bash ping.sh運行它時,我一直在使用這個基本的腳本獲得語法錯誤。 目前的錯誤是: command not found ping.sh: line 9: syntax error near unexpected token etc.這是我的腳本:

    #!/system/bin/sh

# check if the first argument is -all, in which case just ping all
# possible hosts
if [ $# -ge 1 ]; then
    if [ $1 == "-all" ]
    then
        # loop through all IPs
        for ((host=1; host<100; host++))
        do
            ping -c3 192.168.0.$host > /dev/null && echo "192.168.0.$host UP"
        done
    else
        # loop through the hosts passed in
        while test $# -gt 0 # while number of arguments is greater than 0
        do
            ping -c3 $1 > /dev/null && echo "$1 UP" || echo "$1 DOWN"
            shift # shift to the next argument, decrement $# by 1
        done
    fi
else
# if the number of arguments is 0, return a message stating invalid input
    echo "No arguments specified. Expected -all or host names/ip addresses."
    echo "Usage: ping: -all"
    echo "Or: ping: 192.168.0.1,192.168.0.16"
fi

android shell不是GNU bash shell,而是一個POSIX shell(2.x之前的NetBSD Almquist shell,從3.0開始的MirBSD Korn Shell)。

[ $1 == "-all" ]是Bashism, for ((host=1; host<100; host++))是另一個Bashism。

為了使它在POSIX shell中工作,需要重寫一些行:

#!/system/bin/sh

# check if the first argument is -all, in which case just ping all
# possible hosts
if [ $# -ge 1 ]; then
    if [ $1 = "-all" ]
    then
        # loop through all IPs
        host=1; while test $host -lt 100;
        do
            ping -c3 192.168.0.$host > /dev/null && echo "192.168.0.$host UP"
            host=$(($host+1))
        done
    else
        # loop through the hosts passed in
        while test $# -gt 0 # while number of arguments is greater than 0
        do
            ping -c3 $1 > /dev/null && echo "$1 UP" || echo "$1 DOWN"
            shift # shift to the next argument, decrement $# by 1
        done
    fi
else
# if the number of arguments is 0, return a message stating invalid input
    echo "No arguments specified. Expected -all or host names/ip addresses."
    echo "Usage: ping: -all"
    echo "Or: ping: 192.168.0.1,192.168.0.16"
fi

在運行Android 5.1的Google Nexus 10上,這樣的構造按預期工作:

i=0
while ((i < 3)); do
    echo $i;
    ((i++));
done

但是,這樣的結構會導致顯示錯誤消息:

for ((i = 0; i < 3; i++)); do
    echo $i;
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM