1
    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 Answers2

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.

DopeGhoti
  • 76,081
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.

tachomi
  • 7,592