Multiple keyword search in multiple directories bash script

I guess the title is good enough :)
Probably you can do it in single grep command too.. but this way you will play with bash as well..

here is the bash script doing it

 #! /bin/bash
 dirs=(dir1 dir2 dir3 dir4 dir5)
 keywords=(keyword1 keyword2 keyword3 keyword4 keyword5)
 for word in "${keywords[@]}"; do
     strs+=" -e ${word} "
 for path in "${dirs[@]}"; do
     dirname="$(basename "${path}")"
     grep -ir --color ${strs} ${path}

Save this as

and you can run it as bash

See more on bash here

[: too many arguments error in bash script

You are writing shell script and got too many arguments error

While writing bash script, if you got this error, check where you are making expression test like in

if [ $somevar = "value"]; then

if the $somevar is something you are getting it from another command [ say grep or ls] which happen to return a lot of results that are separated by space or something you end up having it being

if [file1 file 2 file 3 = "value"]; then

The easiest solution for this is to enclose the variable in double quote like

if [ -n  "$somevar"]; then
some more commands goes here

Click here to see more on bash

Recommended: Solving Algorithms

Given array of numbers, find k complementary numbers – those which would add up to k. Here is how to solve it

How would you find three numbers that would add to number T from the list of numbers? Compare your solution with this one

With limited memory, and lots of storage, find the missing numbers from a file containing billion numbers in efficient way. Check the attempted solution for it

Simple bash script for searching keyword in the given directories linux

I find myself using grep over and over again for searching some keyword in the same directories. I write this, very simple and almost single usage script to accomplish the task

#! /bin/bash

# Find the given keywork in the given directories #

if [ $# -lt 1 ]; then
    echo $"No Keyword is provided"
    echo $"Usage: ./ needle"


#list where you would want to look inside the directory

directories="dir1 dir2 dir3 dir4 dir5"
for directory in $directories
    if [ -d $directory ]; then
        echo $"Serching in $directory"
        grep -ir --color $keyWord $directory
        echo $"#### Directory $directory does not exist ####"