I am trying to append create a string that will be evaluated in the middle of a grep line. It is to find possible occurrences of different usernames within a certain file. However, I do not know how many usernames there will be. So, I cycle through the array containing the list of usernames and return at output like so "-e username -e username2 -e username3" that will be used in the grep line.

However, this small piece of code seems to be giving me trouble. I've tried several approaches, but UNIX still believes I am trying to pass some sort of command:

    for username in "${usernames[@]}"
        $returnString="$returnString -e $username" #error given, command not found
    echo returnString;

Later, I call the function over here:

declare -a activeUsers=$( who | grep `eGrepUsernames` )

What am I doing wrong in this case?

  • 1
    Drop the first $ -- returnString="......
    – Jeff Schaller
    Jan 18, 2016 at 16:47
  • This will not make the variable local to the for loop? Jan 18, 2016 at 16:51
  • @SepiaSilver The $ operator is the operator to expand a variable to its value. It's not a variable access operator so much as an "insert variable contents here" operator. Jan 18, 2016 at 23:32

2 Answers 2


Your function was trying to evaluate $returnString on the left-hand side during the assignment; instead, you want:

    for username in "${usernames[@]}"
        returnString="$returnString -e $username" # this line changed
    printf '%s ' $returnString;  ## so did this one
  • Thank you - there is no error now, but strangely, "-e" is still not be appended to the string - only the username is. Jan 18, 2016 at 17:14
  • we both got caught by echo seeing the -e as an option instead of as text to be printed. I updated the answer to use printf instead.
    – Jeff Schaller
    Jan 18, 2016 at 17:23
  • For some great background, see: unix.stackexchange.com/a/65819/117549
    – Jeff Schaller
    Jan 18, 2016 at 17:25
  • Thank you for clearing up that massive misunderstanding and providing that resource! Jan 19, 2016 at 6:12

declare is a bash-only command, that's the equivalent of typeset in ksh or zsh.

dash has no equivalent command and has no array support other than with "$@".

The way to go here is to store the list of user names in a newline delimited list:


And use:

who | grep -F "$users"

However, that will look for me, you or someone anywhere in the who output (note that someone does contain me for instance).

Some grep implementations have a -w to search for words only.

You would probably want to check for the first column of the who output (assuming none of your users have blanks in their user names):

users="me you someone"
grepUsernames() {
  awk -v u="$users" '
    BEGIN{split(u, a); for (i in a) users[a[i]]}
    $1 in users'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .