[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: 'official function declaration format' doesn't work if alias defined

From: Reuti
Subject: Re: 'official function declaration format' doesn't work if alias defined
Date: Thu, 7 Jan 2016 02:30:39 +0100


Am 07.01.2016 um 00:49 schrieb Linda Walsh:

> I had an alias referring to printf that I wanted to replace
> with a function.
> instead of using the function declarator
> 'function' (or my alias 'sub'), I remembered that the official
> way was to use:
> P () {
>   ...
> }
> But then ran into problems with the alias taking precedence over the
> function.
> Even in the file where the function was defined and exported, I got
> an error in the export statement about "P" not being a function.
> I also tried unaliasing it:
> unalias P >& /dev/null || ((1))
> export -f P Pe
> But still got the "not a function" ... then I realized
> I had used the official, POSIX format for function declarations,
> above, but guess it had silently been changed into
> printf () {
>   ...
> }
> by the 'alias'. 

Yep. You redefined printf().

> Sure enough, using the old form:
> function P () {
>   ...
> }
> caused "P" to be defined as a function -- so when it was
> unaliased and exported, the export statement found the function.
> I am not sure how one would catch a problem like that other than
> by make sure the defined function is never the 1st argument on the line
> (by adding function).

Yep, without the "function" keyword the alias will be used also for replacing 
the name of the to be defined function:

$ alias P=foo
$ P () { echo baz; }
$ foo
$ type P
P is aliased to `foo'
$ type foo
foo is a function
foo () 
    echo baz

as it's the first word.

>  Seems like using 'function' is safer.
> Perhaps the idea of leaving off "function" at the beginning of a function
> isn't such a good practice?

Even if you use it: someone could define an alias named function - and this 
stands for all commands.

In some cases it might be possible to check the exit code of `alias P` resp. 
`type P` beforehand, or to remove with "unalias -a" all aliases.

-- Reuti

reply via email to

[Prev in Thread] Current Thread [Next in Thread]