在Bash中,如何为"export GREP_COLOR ='1; 32'; grep --color"编写别名或函数?

nop*_*ole 4 bash grep

grep 不允许设置颜色

grep --color='1;32'
Run Code Online (Sandbox Code Playgroud)

(1表示粗体,32表示绿色).它必须使用GREP_COLOR

export GREP_COLOR='1;32'
Run Code Online (Sandbox Code Playgroud)

然后使用 grep --color

我们如何为grep别名或编写函数,以便我们有两个版本的grep(比如grep和grepstrong),一个用于通常的绿色字体,另一个是带有黑色(或白色)背景的绿色字体?

alias grep='export GREP_COLOR="1;32"; grep --color'
Run Code Online (Sandbox Code Playgroud)

如果我们使用,将不起作用

grep some_function_name | grep 3
Run Code Online (Sandbox Code Playgroud)

然后上面的别名将生成grep和pipe的结果export,所以第二个grep根本不会得到任何输入而只是在那里等待.

Sea*_*ean 7

使用bash,您可以通过在命令前加上"key = value"对来为单个命令设置环境变量:

GREP_COLOR='1;32' grep --color <whatever>
Run Code Online (Sandbox Code Playgroud)

例:

echo foo | VAR=value bash -c 'read line; echo $VAR: $line'
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下,只需说:

alias grep='GREP_COLOR="1;32" grep --color'
Run Code Online (Sandbox Code Playgroud)