【问题标题】:Trouble with android bash shell scriptandroid bash shell脚本的问题
【发布时间】:2013-04-19 16:08:50
【问题描述】:

每当通过调用 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

【问题讨论】:

  • 设备是否有 ping 可执行文件。使用adb shell查找
  • 您的设备没有 ping。您通常期望在 linux 安装中找到的只有一小部分实际上在设备上,并且因型号而异。除了 ls 和 rm,你不能指望更多。
  • 您最好尝试通过 java 代码执行此操作,查看此问题及其答案:*.com/questions/11506321/…
  • Android 设备通常没有 bash - 它们有一个非常有限的 shell,来自为 Android 创建的工具箱包。一些定制的 rom 也有一个busybox shell,或者取而代之。移植实际的 bash 是可能的,并且可能已经完成,但会有点不寻常。

标签: android bash shell syntax


【解决方案1】:

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

[ $1 == "-all" ] 是 Bashism,for ((host=1; host&lt;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

【讨论】:

    【解决方案2】:

    在运行 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
    

    【讨论】:

      最近更新 更多