0
    ROOTPATH="/path/here"
    p1 = "file1"
    p2 = "file2"

    for file in `find $ROOTPATH type f`; do
    if [["$file" =~ $p1]]; then
      echo 'got p1'
    elif [["$file" =~ $p2]]; then
      echo 'got p1'
    else

    echo 'got nothing'

This fails, and I'm not sure why. Both $p1 and $p2 are strings, and so is file.

Im trying to do a comparison on (2) strings, to see if $p1 or p2 exist in $file on two separate conditions.

What am I doing wrong?

2

You are missing required syntax to use find's "search-by-type" operator:

for file in $(find "$ROOTPATH" -type f); do

Your assignation of the p1 and p2 variables are syntactically incorrect:

p1="file1"    # Assigns the value 'file1' to the variable p1
p1 = "file1"  # Attempts to execute `p1` with arguments '=' and 'file1'

Also, the two echo statements are identical, you might want to alter the second case's echo command, depending upon your use case.

Further, the syntax of your if statements is flawed; a whitespace character or command separator is required both before and after the [[ and ]] tokens.

| improve this answer | |
  • It also worth to mention about missed spaces [["$file" ... – RomanPerekhrest Oct 16 '17 at 16:04
  • Can you elaborate where im missing spaces please – john jones Oct 16 '17 at 16:07
  • @johnjones you need spaces as in [[ "$file" .... ]]. Though quoting the variable within [[ is not necessary. Also looping through find as mentioned by @DopeGhoti is wrong. – Valentin Bajrami Oct 16 '17 at 17:24
  • Try something like this: find . -type f -exec sh -c 'for file; do [[ $file == *file1* || $file == *file2* ]] && echo "Got $file"; done' _ {} +. Another note. =~ matches regular expression. It matches f i l e 1. – Valentin Bajrami Oct 16 '17 at 17:28
0

Just fixing the syntax

ROOTPATH="/path/here"
p1="file1"
p2="file2"

for file in `find $ROOTPATH -type f`; 
do
    if [[ $file =~ $p1 ]]; 
    then
        echo "got p1"
    elif [[ $file =~ $p2 ]]; 
    then
        echo "got p2"
    else
        echo "got nothing"
    fi
done

Arrangement

  • Removing spaces in variable assignment
  • -type instead of type
  • Removed " in variable $file because of [[ usage
  • Added space ([[ $file & p1 ]])
  • Adding fi & done terminations

As commented in comments, please be aware of looping with find command.

| improve this answer | |
  • @JeffSchaller Thanks for the heads up – tachomi Oct 16 '17 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.