我有一些冗长的脚本相互调用,我希望它们的输出更具描述性。其思想是为每个脚本定制echo命令,如下所示。
我的问题是,如何使用echo使其非递归?
这是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

这是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

所以输出应该是:
>./script1.sh
script1: Info
script2: Info

---编辑
奖金:
>./script1.sh 2> /dev/null
Info
Info

最佳答案

使用builtin关键字:

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

这里是帮助页:
$ 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..

08-18 02:10