android - android bash shell脚本的问题

标签 android bash shell syntax

每当通过调用 bash ping.sh 在 android 上运行这个有点基本的脚本时,我总是遇到语法错误。当前错误是 : 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(NetBSD Almquist shell 2.x 之前,MirBSD Korn Shell 从 3.0 开始)。

[ $1 == "-all" ]是巴什主义,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 - android bash shell脚本的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16108940/

相关文章:

linux - windows环境下运行Linux Shell脚本

linux - bash:获取以给定字符串开头的命令列表

windows - 在Windows的Bash上运行Elasticsearch 1.7.1的问题

android - 在 fragment 中添加 GoogleMap 时的 NPE

ICS 上的 Android PorterDuffXfermode

java - 获取蓝牙信号强度

linux - crontab 执行 shell 脚本 : Mount error(13): Permission denied

bash - 在 Bash 脚本中随机选择并打印三个字符串之一

bash - 可能的攻击 : echo -e

android - 我可以在谷歌地图中拥有最大数量的叠加层吗?