In this small for loop I created, I need the loop to print this message only once for all arguments.

for arg in $@
        echo "There are $(grep "$arg" cis132Students|wc -l) classmates in this list, where $(wc -l cis132Students) is the actual number of classmates."

What contains in $arg is a few names that do exist in the file, and a couple of names that do not exist in the file. What happens is that the loops prints that message multiple times for each argument, where I only want it to print once.

  • By using $@ the parameters are expanded to a separste word and then grep is run for each one which is why the message is repeated for each instance. Commented May 3, 2019 at 19:39

2 Answers 2


You don't want to loop through the arguments, this is reading them one at a time causing your echo statement to execute once for each argument.

You can do something like the following:


p=$(echo "$@" | tr ' ' '|')
ln=$(wc -l "$student_file")
gn=$(grep -cE "$p" "$student_file")

echo "There are $gn classmates in the list, where $ln is the actual number of classmates."

p: Will be converted into a string that can be fed to grep in extended regex mode. For example if you provide arguments: jesse jay it will be convered to jesse|jay
ln: Will be the total number of lines (students) in your input file
gn: Will be the number of students that have matched your argument search


Another solution:

$ cat cis132Students
$ cat file
$ echo "There are $(grep -cf file cis132Students) classmates in this list, where $(wc -l <cis132Students) is the actual number of classmates."
There are 2 classmates in this list, where 3 is the actual number of classmates.
  • grep -cf file cis132Students: parameter -f file takes file as pattern input file for grep and -c counts the matching lines
  • wc -l <cis132Students outputs the line count without the filename

You must log in to answer this question.

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