【问题标题】:"function: not found" error under Termux shTermux sh 下的“function: not found”错误
【发布时间】:2017-09-10 17:32:57
【问题描述】:

启动脚本testyon.sh后:

#!/bin/sh 
function yon { 
while true; do 
echo "Start proc?[Y/n]: "
read -r "[Y/n]: " yn 
case $yn in 
[Yy]*) echo "Starting" ; return 0 ;;
[Nn]*) echo "Stopped" ; return 1 ;; 
esac 
done }

我收到此错误:

$ sh testyon.sh
testyon.sh: 2: testyon.sh: function: not found
testyon.sh: 7: testyon.sh: Syntax error: newline unexpected (expecting ")")
$

如何解决?

【问题讨论】:

    标签: android shell termux


    【解决方案1】:

    我猜当你调用 sh 时运行的任何 shell 都会被函数语法抛出。声明函数的可移植方式是

    yon() { 
        while true; do 
            echo "Start proc?[Y/n]: "
            read -r "[Y/n]: " yn 
            case $yn in 
                [Yy]*) echo "Starting"; return 0 ;;
                [Nn]*) echo "Stopped"; return 1 ;; 
            esac 
        done
    }
    

    参考:POSIX 规范,Shell 命令语言,Function Definition Command

    两个备注:

    • 您似乎提示了用户两次,但我不确定read -r 命令中的提示是否有任何作用。实际上,它似乎首先阻止将任何内容读入yn
    • Termux 附带一个完整的 Bash,位于 /data/data/com.termux/files/usr/bin/bash,这将防止您的功能问题。

    【讨论】:

    • 我认为我们可以相当肯定 whatever shell 确实 POSIX shell。如果 OP 将其显式调用为 bash 或 Zsh,则错误消息的措辞会有所不同。
    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 2017-05-26
    • 2020-01-28
    • 1970-01-01
    • 2018-06-06
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多