0

I am about to create a frame as a function, around my title, but when I call the function I always get a message, function not found. I can't find why it is not working.

The error I get:

banner.sh: 3: function: not found
+-+
banner.sh: 11: Syntax error: "}" unexpected

Code snippet:

function cover {
    length=${#1}
    echo -n '+'
    for i in {0..$length-3}
    do
        echo -n '-'
    done
    echo '+'
}

At the end I would just call the function like that:

cover
echo "previously declared string variable"
ajmeese7
  • 244
  • 2
    Please [edit] your question and show us the entire script. While the code you show won't work (you can't use variables inside brace expansions and you can't do mathematical operations like that either), it also won't produce the error you mention. So please show us the entire script and also tell us how you launch it (/path/to/banner.sh? sh banner.sh? bash banner.sh? something else?). – terdon Dec 05 '22 at 10:38
  • {0..$length} is ksh compatible – Gilles Quénot Dec 05 '22 at 10:44
  • @GillesQuenot but even in ksh, you can't use {0..$length-3} without it becoming a concatenation of the value of $length and the string -3. And, in any case, the OP seems to be using bash. – terdon Dec 05 '22 at 10:51
  • There a re two immediate issues here, and these are 1) you are running the script with something that is not bash, and 2) you can't use a variable (or integer expression) as the end of a range used in a brace expansion in bash. – Kusalananda Dec 05 '22 at 13:19

1 Answers1

0

You're using non-standard syntax and running the script with a standard shell.

function foo is the ksh syntax for functions, it's supported by Bash as a synonym for the standard foo().

But in a standard shell, function foo { runs the command function with the two arguments foo and {. You don't have a command with that name, so you get the error. At the end, there's no open brace group when the keyword } appears, so that also gives a syntax error.

The exact spelling of the error messages looks like you're running Dash, used as /bin/sh in Debian and Ubuntu, and which (mostly) only supports standard POSIX syntax.

Either use POSIX syntax with a POSIX shell, or use Bash with Bash syntax.

Though note that {0..$length-3} doesn't work in any shell (as far as I can find), see e.g. In bash, is it possible to use an integer variable in a brace expansion

To loop over a set of numbers, you could use for (( .. )) (in Bash/ksh/zsh):

for ((i = 0; i < length - 3; i++)) do
    ...
done
ilkkachu
  • 138,973