0

I have a bash script containing multiple echo calls:

 #!bin/bash
 echo 'a'
 echo 'b'
 echo 'c'

I want to prepend a default text to all of these echo calls to get an output like this:

default_text: a
default_text: b
default_text: c

Is there a way to do this globally inside the script without adding the default text to each one of the echo calls?

Note: Below there are 2 very good answers to this question. The one accepted resolves the problem specifically for echo commands. The second one resolves the problem globally inside the script for any command that outputs to stdout.

4

3 回答 3

9

定义一个函数:

function echo {
    builtin echo 'default_text: ' "$@" ;
}

是必需的builtin,否则函数将是递归的。

于 2013-07-24T10:25:54.950 回答
3

这种 bash 技术适用于任何将文本发送到标准输出的命令:

exec 1> >(sed 's/^/default text: /')
$ echo foo
default text: foo
$ date
default text: Wed Jul 24 07:43:38 EDT 2013
$ ls
default text: file1
default text: file2
于 2013-07-24T11:46:21.317 回答
0

尝试这个:

shopt -s expand_aliases
alias echo="echo 'default_text: '"
于 2013-07-24T10:25:42.007 回答