Wednesday, April 6, 2022

[SOLVED] "function: not found" error under Termux sh

Issue

After starting script 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 }

I am getting this error:

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

How to solve this?


Solution

I guess whatever shell is run when you call sh is thrown off by the function syntax. The portable way of declaring a function is

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
}

Reference: POSIX spec, Shell Command Language, Function Definition Command.

Two remarks:

  • You seem to prompt the user twice, but I'm not sure if the prompt in the read -r command does anything at all. It actually seems to prevent reading anything into yn in the first place.
  • Termux comes with a full blown Bash living at /data/data/com.termux/files/usr/bin/bash, which would prevent your function problem.


Answered By - Benjamin W.
Answer Checked By - Clifford M. (WPSolving Volunteer)