Exclude items in a list in a bash script

In a Linux bash script you can loop over a set of data like a list of directories, database table names etc.
But you do not always want to use all the items in this list so you need to filter the results.

In this example I will use a generated list of directory names.
Filtering the directories we want to exclude is done by removing them from the directory listing using sed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
DIRS=`ls -l --time-style="long-iso" $MYDIR | egrep '^d' | awk '{print $8}'`

# make a list of directories you want to exclude
$DIREXCLUDE="dir1 dir3 dir5"

# now remove the excluded directories from the directory list by looping over the directories and remove the excluded directories with sed:
for EXCLUDE in $DIREXCLUDE
do
    DIRS=`echo $DIRS | sed "s/\b$EXCLUDE\b//g"`
done

# and finally loop over the cleaned up directory list.
for DIR in $DIRS
do
    echo  ${DIR} :
done

* see a previous article about selecting directory names in a cron job.

Related posts

Tags: , , ,

3 Responses to “Exclude items in a list in a bash script”

  1. anonimus maximus says:

    $DIREXCLUDE=”dir1 dir3 dir5″

    tries to execute defined string
    it needs to be:

    DIREXCLUDE=”dir1 dir3 dir5″

    (no dolla)

  2. Andrei,

    This code works for me, no errors. A “command not found” means that your OS does not understand the request. Are the sed, awk and egrep commands available for you?

  3. andrei says:

    something is wrong with your code.

    I receive this error: line 20: =dir1 dir3 dir5: command not found

Leave a Reply