2

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:

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

Later, I call the function over here:

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

What am I doing wrong in this case?

2 Answers2

2

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

eGrepUsernames(){
    returnString="";
    for username in "${usernames[@]}"
    do
        returnString="$returnString -e $username" # this line changed
    done
    printf '%s ' $returnString;  ## so did this one
}
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
1

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:

users="me
you
someone"

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'
}