Using whoami to search for files that mention user

The pathname of the file is given as a parameter. This means that it's given on the command line of the script. This means that you shouldn't interactively ask the user for it.

#!/bin/sh
grep -wF -e "$LOGNAME" "$1"

Alternatively, if you really want to use whoami:

#!/bin/sh
grep -wF -e "$(whoami)" "$1"

Or, for the "two lines" requirement:

#!/bin/sh
name=$(whoami)  # or:  name=$LOGNAME
grep -wF -e "$name" "$1"

Or, if we'd like to do something useful on that first line:

#!/bin/sh
[ ! -f "$1" ] && { printf 'No such file: %s\n' "$1" >&2; exit 1; }
grep -wF -e "$(whoami)" "$1"

The -w option to grep make it match complete words only. grep -w 'AA' would match AA but not AAA.

The -F option to grep makes the utility take the given expression as a fixed string and not as a regular expression.

The -e option signifies that the next string on the command line is the pattern. Without it, a pattern starting with a dash may be mistakenly interpreted as a set of command line options.

The $LOGNAME (or $USER on many systems) variable holds the username of the current user.

The value of $1 is the first command line argument given to the script on the command line.

Also note that we may execute this with /bin/sh rather than with bash as this script uses no special bash-specific shell extensions. It would obviously run just as well under bash...


Note that the above does not search for files mentioning a particular user (as in the title of the question), but rather searches for lines in a file that mentions this user.

To search for files mentioning the current user in a directory given on the command line:

#!/bin/sh
find "$1" -type f -exec grep -q -wF -e "$LOGNAME" {} ';' -print

Related to this last part:

  • Understanding the -exec option of `find`
  • man grep on your system.