Bash 脚本的彩色输出

Son*_*nny 3 grep bash shell-script

我在grepbash 脚本中运行。如果我grep直接运行命令,我会看到文件名和搜索字符串的彩色输出:

grep -i username /tmp/sess_*
Run Code Online (Sandbox Code Playgroud)

如果我将该命令放在 bash 脚本中,它可以工作,但颜色会丢失。如何保留彩色输出?

Eri*_*ouf 5

你可以添加--color=always到你的grep。

我本地联机帮助页中的相关部分:

  --color[=WHEN], --colour[=WHEN]
          Surround  the  matched  (non-empty)  strings,  matching   lines,
          context  lines,  file  names,  line  numbers,  byte offsets, and
          separators (for fields and groups of context lines) with  escape
          sequences  to display them in color on the terminal.  The colors
          are  defined  by  the  environment  variable  GREP_COLORS.   The
          deprecated  environment  variable GREP_COLOR is still supported,
          but its setting does not have priority.  WHEN is never,  always,
          or auto.
Run Code Online (Sandbox Code Playgroud)

正如SO 上的这个问题所暗示的那样,您可能有一个别名grep,将其映射到grep --color=auto.bashrc的脚本中,但脚本未读取该别名,因此未在脚本中应用。