从 bash 脚本运行时 grep 失去颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9550885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
grep loses coloring when run from bash script
提问by jairbow
I wrote a simple bash script because I was using a grep command with the same arguments, repeatedly. I'm running it from ~/bin and it runs just fine.
我编写了一个简单的 bash 脚本,因为我反复使用具有相同参数的 grep 命令。我从 ~/bin 运行它,它运行得很好。
My problem is: All the coloring is gone when it's run through my bash script. The exact same command put right into the commandline nicely color codes line numbers, filenames, etc.
我的问题是:当它通过我的 bash 脚本运行时,所有的颜色都消失了。完全相同的命令放在命令行中很好地对行号、文件名等进行了颜色编码。
Here's my bash script
这是我的 bash 脚本
#!/bin/bash
# grep php files inside of myfolder, recursively and with line numbers
grep -rn --include="*.php" "" /home/me/myfolder/
回答by Fred Foo
You've probably defined grepas an alias for grep --color=autoin your .bashrc, but that's not loaded by scripts. Use an explicit grep --colorin your script.
您可能已经在您的中将其定义grep为别名,但脚本并未加载该别名。在脚本中使用显式。grep --color=auto.bashrcgrep --color
回答by PlexQ
When you run a script, a new shell is spawned to do so. This new environment doesn't have the same settings as your default shell. As to how to get the coloring back, I'm not sure. You might try sourcing your profile at the start of the script:
当您运行脚本时,会生成一个新的 shell 来执行此操作。这个新环境与您的默认 shell 没有相同的设置。至于如何恢复着色,我不确定。您可以尝试在脚本开头获取您的个人资料:
#!/bin/bash
source $HOME/.bash_profile
or whichever file makes sense on your particular unix flavor (.profile, .bash_rc, .bashrc .bash_profile) to name a few.
或者任何对您的特定 unix 风格有意义的文件(.profile、.bash_rc、.bashrc .bash_profile)等等。

