Henry Brice
Henry Brice

Reputation: 294

multiple conditions on 'if'

I'm trying to write a bash script that loops over directories that start with one of two strings in a given folder. I wrote the following:

for aSubj in /wherever/*
    if [ [ -d $aSubj ] && [ [ $aSubj == hu* ] || [ $aSubj == ny* ] ] ]; then
        .
        .
    fi
done

When I try and run this I get a syntax error on the line of the 'if': syntax error near unexpected token 'if'

Can anyone point out where I'm going wrong?

Upvotes: 0

Views: 105

Answers (2)

fedorqui
fedorqui

Reputation: 289725

If you want to mention multiple conditions, just nest them with ( ):

$ d=23
$ ( [ $d -ge 20 ] && [ $d -ge 5 ] ) || [ $d -ge 5 ] && echo "yes"
yes

However, in this case you may want to use a regular expression as described in Check if a string matches a regex in Bash script:

[[ $aSubj =~ ^(hu|ny)* ]]

This checks if the content in the variable $aSubj starts with either hu or ny.

Or even use the regular expression to fetch the files. For example, the following will match all files in ttt/ directory whose name starts by either a or b:

for file in ttt/[ab]*

Note you can also feed your loop with using a process substitution with find containing a regular expression (samples in How to use regex in file find):

while IFS= read -r file
do
   # .... things
done < <(find your_dir -mindepth 1 -maxdepth 1 -type d -regex '.*/\(hu\|ny\).*')

For example, if I have the following dirs:

$ ls dirs/
aa23  aa24  ba24  bc23  ca24

I get this result if I look for directories whose name starts by either ca or bc:

$ find dirs -mindepth 1 -maxdepth 1 -type d -regex '.*/\(ca\|bc\).*'
dirs/bc23
dirs/ca24

Upvotes: 1

timrau
timrau

Reputation: 23058

The 1st line should be

for aSubj in /wherever/*; do

Upvotes: 1

Related Questions