Search code examples
bashoverloadingverbosity

bash: override echo to print a custom prefix in a script


I have some lengthy scripts calling each other and I want their output to be more descriptive. The idea is to customize the echo command for each script with something like below.

My question is, how to make it non recursive, using echo?

this is script1.sh

#!/bin/bash
#Original version:
#function echo(){ echo $(basename $0 .sh): $1; }
#Version after fixes
function echo(){ builtin echo -n "$(basename $0 .sh): ">&2; builtin echo $@ ; } 
echo Info
./script2.sh

this is script2.sh

#!/bin/bash
#Original version:
#function echo(){ echo $(basename $0 .sh): $1; }
#Version after fixes
function echo(){ builtin echo -n "$(basename $0 .sh): ">&2; builtin echo $@ ; } 
echo Info
exit 0

so the output should be:

>./script1.sh
script1: Info
script2: Info

--- EDIT

Bonus:

>./script1.sh 2> /dev/null 
Info
Info

Solution

  • use the builtin keyword:

    function echo(){ builtin echo $(basename $0 .sh): $1; }
    

    here the help page:

    $ help builtin
    builtin: builtin [shell-builtin [arg ...]]
        Execute shell builtins.
    
        Execute SHELL-BUILTIN with arguments ARGs without performing command
        lookup.  This is useful when you wish to reimplement a shell builtin
        as a shell function, but need to execute the builtin within the function.
    
        Exit Status:
        Returns the exit status of SHELL-BUILTIN, or false if SHELL-BUILTIN is
        not a shell builtin..