22

I had to grep recently for a password that may have been saved in a file. I did not want that line to show up in the bash history.

How can I prevent a password or other sensitive information from being stored in the bash history when using grep? For example, how can I get grep to read the pattern from stdin or console?

3 Answers 3

37

If you put HISTCONTROL=ignorespace in your .bashrc, and you put a space before the command name, it will not be added to your history.

$ export HISTCONTROL=ignorespace
$ grep "passwd" secret_password_file.txt   # added to history
$  grep "passwd" secret_password_file.txt  # not added to history
3
  • 3
    FWIW: The question in the title and the question in the body are completely different. I answered the question in the title.
    – user235731
    Jul 25, 2013 at 17:12
  • Your criticism is appropriate. I just edited the title. Is it better now? I still think (and so it seems does the community) that your answer is the most relevant.
    – Leo
    Jul 26, 2013 at 5:11
  • 1
    I made an edit to your question to clarify things, making both questions (preventing something from being stored in the history and reading from stdin with grep) available. This way, all answers are still valid, but the very different solutions won't be confusing.
    – user235731
    Jul 26, 2013 at 9:32
6

Just for completeness, I answer the question in the body: how to get grep to read patterns from stdin:

You can use the -f option:

grep -f- /path/to/file

That will read any number of patterns from stdin, one per line. (- means stdin; you could also specify a file with patterns, one per line.) grep will match lines in /path/to/file which match any of the specified patterns.

1
  • Thanks for that. That is a good contribution and a handy trick to use elsewhere as well, say when an or'ed pattern is needed
    – Leo
    Jul 26, 2013 at 5:12
2

This is the best I could come up with:

grep $(read -p "Pattern: "; echo $REPLY) .*

Is this safe enough? Is there anyway to recover the pattern other than scrolling the terminal? Is there a nicer way?

2
  • 4
    You can use read -s to prevent echo (see also this question). The secret will be visible in ps output though. You can use instead grep -f /dev/stdin * (or grep -f - *) so that grep will read the pattern(s) from a file instead, end input with ^D, or: (read -es; echo $REPLY) | grep -f - * Jul 25, 2013 at 16:47
  • 1
    The capture shell should have double quotation marks around it. At the moment, this will break if the user enters spaces or some special characters.
    – user193100
    Jul 25, 2013 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.