0

I wonder if I may use comments in between POSIX shell script's function name and its body? This appears not to throw any problem in shellcheck and runs in Dash / Bash, but searching for this information found me nothing useful.

Example shell functions:

is_int()
# POSIX [bool] function to test one variable for an integer.
{
    case "${1#[+-]}" in
        (*[!0123456789]*) return 1 ;;
        ('')              return 1 ;;
        (*)               return 0 ;;
    esac
}

is_uint()
# POSIX [bool] function to test one variable for an unsigned integer.
{
    case "$1" in
        ([+-]*) return 1 ;;
    esac
    is_int "$1"
}

Would any shell have known problem with this? I would not like if it hurt the portability of some of my scripts.


Attention, I only use this very recently and because VS Codium I started using supports function blocks collapsing like that:

VS Codium function blocks collapsing

Thank you.

PS: I like the comments describing functions in my shell scripts this way a bit more than having the comment above f()'s name. It is only cosmetic problem and as such please refrain from discussing the Why not above function's name. Thank you!

1 Answer 1

2

I think it is valid. The POSIX shell grammar defines a function like

function_definition : fname '(' ')' linebreak function_body
                 ;
linebreak        : newline_list
                 | /* empty */
                 ;
newline_list     :              NEWLINE
                 | newline_list NEWLINE
                 ;

So you can have any number of linebreaks, including zero, between () and your function body.

And, for token recognition:

  1. If the current character is a #, it and all subsequent characters up to, but excluding, the next <newline> shall be discarded as a comment. The <newline> that ends the line is not considered part of the comment.

I interpret this as follows: this

is_int()
# POSIX [bool] function to test one variable for an integer.
{

is equivalent to

is_int()
{

and thus valid.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.